Rails belongs_to many models

Zabba picture Zabba · Oct 12, 2010 · Viewed 24k times · Source

I did find some questions on SO about Rails associations that are somewhat like my question, but for the life of me I can't seem to understand how to use belongs_to multiple models.

Here's the table structure I intend to have:

User
 id

Post
 id
 user_id #foreign key; a post belongs to a User aka "Who created this post"

Comment
 id
 user_id #foreign key; a comment belongs to a User aka "Who made this comment"
 post_id #foreign key; a comment belongs to a Post aka "What post this comment is for"

And the associations:

User
 has_many :posts
 has_many :comments

Post
 belongs_to :user
 has_many :comments

Comment
 belongs_to :user
 belongs_to :post

Is this the correct approach?

Answer

Maxem picture Maxem · Oct 12, 2010

Yes that is the correct approach.