Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails belongs_to many models [closed]

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?

like image 655
Zabba Avatar asked Oct 12 '10 05:10

Zabba


People also ask

Can a model belong to multiple models?

Yes a model can belong to more than one model.

What is difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user .

What is a polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

How associations work Rails?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.


1 Answers

Yes that is the correct approach.

like image 68
Maxem Avatar answered Sep 19 '22 09:09

Maxem