Given
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 Posts in the controller via
@post = current_user.posts.build(params[:post])
My question is, how do I set/save/edit the @post model such that the relationship between the post and the discussion is also set?
Save and edit discussions along with post
Existing Discussion
To associate the post you’re building with an existing discussion, just merge the id into the post params
You will have to have a hidden input for discussion id in the form for
@postso the association gets saved.New Discussion
If you want to build a new discussion along with every post and manage its attributes via the form, use
accepts_nested_attributesYou then have to build the discussion in the controller with
build_discussionafter you built the postAnd in your form, you can include nested fields for discussions
This will create a discussion along with the post. For more on nested attributes, watch this excellent railscast
Better Relations
Furthermore, you can use the
:throughoption of thehas_manyassociation for a more consistent relational setup:Like this, the relation of the user to the discussion is maintained only in the
Postmodel, and not in two places.