Home Correct way to build multiple belongs_to association
Reply: 0

Correct way to build multiple belongs_to association

user10617 Published in September 20, 2018, 12:44 pm

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
    add_foreign_key :contents, :data_books, on_delete: :cascade
    add_foreign_key :contents, :clients, on_delete: :cascade

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:

             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?

share|improve this question
  • Nothing inherently wrong with what you're doing. If you were in the ClientsController you could do something like @content_databook = DataBook.find(content_creation_params[:data_id]); @content = @client.build_content(room_name: @room_name, data_book: @content_databook). You could do a similar thing if starting in DataBooksController. That's a standard pattern, but it depends on the full situation and what makes most sense. – dave_slash_null Feb 9 at 19:37
  • I ended up creating it in the model as 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 Which is similar to your suggestion I think – anonn023432 Feb 9 at 19:46
  • FYI, you're table is being created incorrectly. create_table :create_content will create a table called "create_content". You need to do create_table :contents instead. – jeffdill2 Feb 9 at 19:49
  • @jeffdill2 sorry that was an error while writing the question over here. I'll correct it in the question – anonn023432 Feb 9 at 19:50
  • @anonn023432 right on. :thumbsup: – jeffdill2 Feb 9 at 19:51

1 Answer 1

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO