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.
Beat Richartz Jul 18 2018-12-18T00: 00Z
source share