Rails belongs_to many models [closed]
Asked Answered
F

2

55

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?

Freberg answered 12/10, 2010 at 5:22 Comment(2)
How do you go ahead to perform a save on comments?Hornet
omg, it's been 7 years since I learnt rails (thank you SO!). To answer your question @MosesNdeda, you would instantiate a Comment, assign the user and post objects, and then call save on the Comment object.Freberg
I
59

Yes that is the correct approach.

Iatrics answered 12/10, 2010 at 5:25 Comment(6)
Does this require a join table or anything... or would it work as expected with just what he has shown?Dejadeject
These are one to many relationships (one user has many posts etc.), therefore no. The comments table should look like this: id user_id post_id and ofc content or whatever.Iatrics
can you type has_many :posts, :commentsMuimuir
Question: In the first post you would do: current_user.post.build(params[:post]) but in the comment how would you attribute both the user id and the post id in the comment without a hidden field with the post id?Hereby
This question and it's answer explain how to do this very well: #11539651Trellas
As if you got 25 up votes and a correct answer out of that, nicely donePresber
E
10

While not always the "best" approach, Rails offers what's called a Polymorphic belongs_to association. It prevents you from defining a foreign key in the database because the xxx_id column is referencing an id in one of many possible tables while another column designates the name of that table's model, but it makes the relationship more explicit in Rails. Also, it restricts the model to only belong to one of the other models, as opposed to belonging to one or more, as it would happen using the setup of multiple foreign keys without some additional db magic.

Edmiston answered 16/7, 2011 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.