Home Correct way to build multiple belongs_to association
Reply: 1

Correct way to build multiple belongs_to association

anonn023432
1#
anonn023432 Published in 2018-02-09 19:02:05Z

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?

jeffdill2
2#
jeffdill2 Reply to 2018-02-09 19:54:53Z

You can accomplish what you need any number of ways, all of which being valid.

# 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.
...
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO