'How to create an object that belongs to two models
Is there any way by which i can create an object of a model that belongs to two other models for example if i have users who have many posts and then posts which can have many comments and comments belongs to both user and post. if i do post.comments.create() it will associate only post with comment and if i do user.comments.create() then it will associate user. If i want to associate both with comments then what's the method for that. I know i can use polymorphic association but is there any other way too?
Solution 1:[1]
You can use belongs_to with both models. The only difference is that while creating a comment you'll have to explicitly mention the id of the model you're not creating through. I'll give an example:
class Comment
belongs_to :user
belongs_to :post
end
comment = post.comments.create(user_id: some_user_id)
Since I created the comment via the post comments relation the post id will automatically get inserted to the comment's post_id attribute. I specifically mentioned the user_id so that comment.user will return the user which has an id of some_user_id.
EDIT
When creating the comment, to use the comments attributes in the params hash use the following:
comment = post.comments.build(params[:comment])
comment.user_id = some_user_id
comment.save
Solution 2:[2]
It might be even more intuitive to create the Comment like this:
comment = Comment.create(user_id: user-you-want-to-associate.id, post_id: post-you-want-to-associate.id)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jillian Hoenig |
