Rails associations of user/post/comment
- by garthcn
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!