Reputation: 229
I'm trying to create an app like a blog, with 3 models: user, post and comment. As expected, a comment belongs to both a user and a post.
I used the following associations:
User.rb
has_many :comments
has_many :posts
Post.rb
has_many :comments
belongs_to :user
Comment.rb
belongs_to :user
belongs_to :post
And I tried to create comments using: @user.comments.create
However, this will relate the comment with user, but not with post. I want the comment to be associated wit BOTH user and post. Is there a way to do so? Or did I use the wrong associations?
I think it might be a bad practice to set the user_id or post_id by hand, so both ids are not in attr_accessible. I'm not sure if it is correct.
Thank you!
Upvotes: 6
Views: 3754
Reputation: 46675
You don't need to set the post_id
, specifically. Try @user.comments.create(:post => @post)
.
Upvotes: 3
Reputation: 8807
If the comment needs to be associated with more than one model, we call it polymorphic association
. You can have a look at has_many_polymorphs
plug-in for that. I presume you are using rails 3, you can try the following:
You can have module defined in the lib/commentable.rb
folder like this:
module Commentable
def self.included(base)
base.class_eval do
has_many :comments, :as => commentable
end
end
end
In the Comment model you should say that it is polymorphic:
belongs_to :commentable, :polymorphic => true
In both, Post and User models you can add the following:
has_many :comments, :as => :commentable, :dependent => :delete_all
Since, in Rails 3 the lib folder is not loaded by default you should ask Rails to load that in your application.rb:
config.autoload_paths += %W(#{config.root}/lib)
Now, Comment is polymorphic and any other model can be associated with it. This should do.
Upvotes: 0