54

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?

Zabba
  • 64,285
  • 47
  • 179
  • 207
  • How do you go ahead to perform a save on comments? – Moses Ndeda Aug 08 '17 at 12:21
  • 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. – Zabba Aug 11 '17 at 05:47

2 Answers2

58

Yes that is the correct approach.

Maxem
  • 2,634
  • 1
  • 20
  • 14
  • Does this require a join table or anything... or would it work as expected with just what he has shown? – Andrew Oct 13 '10 at 04:47
  • 5
    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. – Maxem Oct 13 '10 at 09:17
  • can you type has_many :posts, :comments – Vasseurth Jul 13 '11 at 21:27
  • 1
    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? – Nathan McKaskle Dec 04 '12 at 18:38
  • 4
    This question and it's answer explain how to do this very well: http://stackoverflow.com/questions/11539151/rails-mulitple-belongs-to-assignment – Uri Klar Oct 07 '13 at 14:20
  • As if you got 25 up votes and a correct answer out of that, nicely done – Adam Waite Nov 10 '13 at 12:54
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.

thutt
  • 640
  • 5
  • 18