Ruby on rails model with multiple parents

activerecord, ruby, ruby-on-rails

Solution

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.

Problem

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?

Original source