【问题标题】:Correct way to build multiple belongs_to association建立多个belongs_to关联的正确方法
【发布时间】: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 关联,从 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]),
)

或者有没有更好、更红的方式来做到这一点?

【问题讨论】:

  • 您所做的事情本身并没有错。如果您在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


【解决方案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.
...

【讨论】:

  • 我决定采用 option3,因为这对我来说是最好的方法
  • 正确。根据特定的用例,您可能会在构建更多东西时采用各种不同的方式。
猜你喜欢
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
相关资源
最近更新 更多