【发布时间】:2018-02-09 19:02:05
【问题描述】:
我有一个导轨表,例如:
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 关联,从 contents 到 data_books 和 clients
我不确定为此添加新数据实例的正确方法是什么;官方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]),
)
或者有没有更好、更红的方式来做到这一点?
【问题讨论】:
-
您所做的事情本身并没有错。如果您在
ClientsController中,您可以执行@content_databook = DataBook.find(content_creation_params[:data_id]); @content = @client.build_content(room_name: @room_name, data_book: @content_databook)之类的操作。如果从DataBooksController开始,您可以做类似的事情。这是一个标准模式,但这取决于整个情况以及最有意义的情况。 -
我最终在模型中将其创建为
def self.create!(data_book, client, room_name) @video_call = self.new({ room_name: room_name, client: client}) @video_call.data_book = data_book @video_call.save! end这与我认为的您的建议相似 -
仅供参考,您的表格创建不正确。
create_table :create_content将创建一个名为“create_content”的表。你需要改用create_table :contents。 -
@jeffdill2 抱歉,在此处写问题时出错。我会在问题中纠正它
-
@anonn023432 对。 :thumbup:
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord associations