Rails multiple belongs to assignment

Considering

User:

class User < ActiveRecord::Base has_many :discussions has_many :posts end 

Discussions:

 class Discussion < ActiveRecord::Base belongs_to :user has_many :posts end 

Posts:

 class Post < ActiveRecord::Base belongs_to :user belongs_to :discussion end 

I am currently initializing messages in the controller via

 @post = current_user.posts.build(params[:post]) 

My question is: how to set / save / edit the @post model to establish a connection between a post and a discussion?

+10
ruby ruby-on-rails-3 belongs-to
Jul 18 '12 at 10:18
source share
1 answer

Saving and editing discussions with a message

Existing discussion

To associate the post you are building with an existing discussion, simply merge the id in post params

 @post = current_user.posts.build( params[:post].merge( :discussion_id => existing_discussion.id ) 

You must have hidden input for the discussion identifier in the form for @post so that the association @post .


New discussion

If you want to create a new discussion with each post and manage its attributes through the form, use accepts_nested_attributes

 class Post < ActiveRecord::Base belongs_to :user belongs_to :discussion accepts_nested_attributes_for :discussion end 

Then you need to build a discussion in the controller with build_discussion after you have built the message

 @post.build_discussion 

And in your form you can include nested discussion fields

 form_for @post do |f| f.fields_for :discussion do |df| ...etc 


This will create a discussion with this entry. For more information on nested attributes, see this excellent railscast.


Best relationship

Alternatively, you can use the :through has_many association option for a more consistent relational setting:

 class User < ActiveRecord::Base has_many :posts has_many :discussions, :through => :posts, :source => :discussion end class Discussion < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user belongs_to :discussion end 

Thus, the user's attitude to the discussion is supported only in the Post model, and not in two places.

+12
Jul 18 2018-12-18T00:
source share



All Articles