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?
Yes a model can belong to more than one model.
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 .
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.
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.
Yes that is the correct approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With