Rails associations of user/post/comment

Posted by garthcn on Stack Overflow See other posts from Stack Overflow or by garthcn
Published on 2011-02-07T06:58:00Z Indexed on 2011/02/07 7:25 UTC
Read the original article Hit count: 161

Filed under:

Hi, I'm trying to create an app like a blog, with 3 models: user, post and comment. As expected, a comment belongs to both a user and a post.

I used the following associations:

User.rb

has_many :comments
has_many :posts

Post.rb

has_many :comments
belongs_to :user

Comment.rb

belongs_to :user
belongs_to :post

And I tried to create comments using: @user.comments.create

However, this will relate the comment with user, but not with post. I want the comment to be associated wit BOTH user and post. Is there a way to do so? Or did I use the wrong associations?

I think it might be a bad practice to set the user_id or post_id by hand, so both ids are not in attr_accessible. I'm not sure if it is correct.

Thank you!

© Stack Overflow or respective owner

Related posts about ruby-on-rails