L
L
l2p2014-02-22 15:51:44
Ruby on Rails
l2p, 2014-02-22 15:51:44

How to connect 3 Ruby on Rails models?

user.rb: has_many :comments
post.rb: has_many :comments
comment.rb:

belongs_to :post
belongs_to :user

Regular comments.
How can I add?
Added without users so: @comment = @post.comments.create(comment_params)
In the table comments user and post:references are registered. It remains only to write a line. Help me please.
And by the way, is it possible to write belongs_to: :post, :user?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
F
FanKiLL, 2014-02-22
@l2p

createcreates an object from the passed parameters and saves it immediately, so adding later
and not saving will not happen.
Instead create, use buildand save by
hand

@comment = @post.comments.build(comment_params)
@comment.user = current_user
@comment.save

T
The Whiz, 2014-02-22
@modernstyle

>And by the way, is it possible to write belongs_to: :post, :user
No
In your case, use has_many, through ( documentation )

F
FanKiLL, 2014-02-22
@FanKiLL

@comment = @post.comments.create(comment_params)
@comment.user = current_user

A
Ant0ha, 2014-02-28
@Ant0ha

> And by the way, is it possible to write belongs_to: :post, :user
There are polymorphic relationships for this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question