Rails belongs_to many models

Ruby on-RailsActiverecordBelongs To

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Yes that is the correct approach.

Solution 2 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZabbaView Question on Stackoverflow
Solution 1 - Ruby on-RailsMaxemView Answer on Stackoverflow
Solution 2 - Ruby on-RailsZhenya SlabkovskiView Answer on Stackoverflow