Reputation: 1041
In my Rails application, I have two models, Articles and Projects, which are both associated with a user. I want to add comments to each of these models. What's the best way to structure this?
Here's my current setup:
class Comment < ActiveRecord::Base
belongs_to :article
belongs_to :project
end
class Article < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Project < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class User < ActiveRecord::Base
has_many :articles
has_many :projects
has_many :comments, :through => :articles
has_many :comments, :through => :projects
end
Is this the right way to handle the structure? If so, how do I manage the CommentsController to have an article_id if it was created through an Article, and a project_id if it was created through a Project? Are there special routes I should set up?
One final comment: Comments don't always have to have a user. Since this if for my website, I want anonymous viewers to be able to leave comments. Is this a trivial task to handle?
Upvotes: 3
Views: 1783
Reputation: 176552
Make Comment
a polymorphic model. Then create a polymorphic association.
Here's an example of polymorphic relationship from the Rails wiki and here's a Railscast from the screencast-men Ryan Bates.
Upvotes: 5
Reputation: 1752
You can check out - acts_as_commentable plugin http://github.com/jackdempsey/acts_as_commentable/tree/master
Or you can proceed with polymorphic relation
Upvotes: 1
Reputation: 143194
You could have ArticleComment
s and ProjectComment
s with similar structure but stored separately, then create a method that returns both types of comments.
Upvotes: -1