我有一个rails表,例如:
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
我的模型指定了从belongs_to
到contents
和data_books
clients
个关联
我不确定为此添加新数据实例的正确方法是什么。官方Rails documentation指定使用build_{association_name}
来执行此操作,但由于我有两种不同的关联,因此无法执行此操作。
这是正确的方法:
Content.new(
data_book: DataBook.find(content_creation_params[:data_id]),
room_name: @room_name,
client: Client.find(content_creation_params[:client_id]),
)
或者是否有一种更好,更红宝石的做法?
答案 0 :(得分:1)
您可以通过多种方式完成您需要的任何方式,所有这些方式都是有效的。
# 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.
...