代码之家  ›  专栏  ›  技术社区  ›  anonn023432

建立多个归属关联的正确方法

  •  1
  • anonn023432  · 技术社区  · 7 年前

    我有一个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
    

    我的模型指定2 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]),
    )
    

    还是有更好、更具红宝石色彩的方法?

    1 回复  |  直到 7 年前
        1
  •  1
  •   jeffdill2    7 年前

    你可以用很多方法来完成你需要的事情,所有这些方法都是有效的。

    # 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.
    ...
    
    推荐文章