Home Correct way to build multiple belongs_to association
Reply: 0

Correct way to build multiple belongs_to association

user1185
1#
user1185 Published in June 23, 2018, 4:31 am

I've a rails table such as:

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

And my model specifies 2 belongs_to associations from contents to data_books and clients

I'm not sure what's the correct way to add new data instance for this; the official Rails documentation specifies using build_{association_name} to do it but I can't do it since I've 2 different associations.

Is this the correct way to do it:

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

Or is there a better, more rubyist way of doing this?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320395 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO