建立多个 belongs_to 关联的正确方法

Correct way to build multiple belongs_to association

我有一个 rails table 例如:

class CreateContent < ActiveRecord::Migration
  def change
    create_table :contents do |t|
      t.references :data_book,  null: false, index: true
      t.string :room_name,  null: false
      t.references :client,  null: false, index: true
      t.timestamps
    end
    add_foreign_key :contents, :data_books, on_delete: :cascade
    add_foreign_key :contents, :clients, on_delete: :cascade
  end
end

我的模型指定了 2 belongs_to 个关联,从 contentsdata_booksclients

我不确定为此添加新数据实例的正确方法是什么;官方 Rails documentation 指定使用 build_{association_name} 来做,但我做不到,因为我有 2 个不同的关联。

这是正确的做法吗:

Content.new(
             data_book: DataBook.find(content_creation_params[:data_id]),
             room_name: @room_name,
             client: Client.find(content_creation_params[:client_id]),
)

或者是否有更好、更符合 ruby​​ist 的方法?

您可以通过多种方式完成您需要的工作,所有方式均有效。

# Option 1
Content.create(data_book: DataBook.create(whatever_params), client: Client.create(whatever_params))

# Option 2
data_book = DataBook.create(whatever_params)
client = Client.create(whatever_params)
content = Content.create(data_book: data_book, client: client)

# Option 3
content = Content.new
content.data_book = DataBook.find(id)
content.client = Client.find(id)
content.save

# Options 4
content = Content.new
data_book = content.build_data_book(whatever_params)
client = content.build_client(whatever_params)
content.save

# Etc. etc. etc.
...