Rails belongs to many models

I found some SO questions about Rails associations that seem like my question, but for my life I can't figure out how to use belongs_to several models.

Here is the table structure that 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 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 right approach?

+46
ruby-on-rails activerecord belongs-to
Oct 12 '10 at 5:22
source share
2 answers

Yes, this is the right approach.

+50
12 Oct '10 at 5:25
source share

Although not always the β€œbest” approach, rails offer what is called polymorphic association. It does not allow you to define a foreign key in the database, because the xxx_id column refers to an identifier in one of the many possible tables, and the other column denotes the name of this table, but makes it more explicit in rails. In addition, it limits the model only to belonging to one of the other models, as opposed to belonging to one or more, since this will happen by installing several foreign keys without additional db magic.

+8
Jul 16 '11 at 19:17
source share



All Articles