views:

171

answers:

2

I have two models, Article and Post that both inherit from a base model called ContentBase.

You can leave comments on both Articles and Posts, so I am using a Polymorphic Association between Comments and Article or Post.

However, since both Article and Post inherit from ContentBase, the commentable_type field ends up being "ContentBase" for both and screws everything up.

Is there a way to specify the commentable_type field in the has_many relationship in Article and Post?

Edit:

By "screws everything up" I mean if there is an Article with ID=1 and Post with ID=1 and I add a Comment with commentable_id=1, commentable_type=ContentBase, that comment will show up for both the Article and Post.

Here's the code:

class Article < BaseContent has_many :comments, :as => :commentable end

class Post < BaseContent has_many :comments, :as => :commentable end

and here's my Comment model:

class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end

+1  A: 

I don't think you want to do that. For polymorphic associations, you want the XXX_type field to be the base model class, not the actual class. I'm not exactly sure of the reason, but I believe it has to do with determining the table name to select from to get the polymorphic data.

I think you need to look at Single Table Inheritance, which is what ActiveRecord uses for storing derived classes in the database. It assumes that since Article and Post are subclasses of ContentBase, they will all be in the same table ("content_bases" by default). If that's the case, you'll never have an Article with ID=1 and a Post with ID=1.

A few references:

Micah
+2  A: 

What's in the ContentBase class? Can you move that code into a module instead of using inheritance?

Module BaseContent
   def self.included(base)
      base.class_eval do
        validates_presence_of     :somefield
        validates_length_of       :someotherfield

        def my_method
          "hello"
        end
      end
   end

end
Mike Breen
There's a bunch of shared functions and validates_length_of for a few shared fields. Is it possible to move it into a module?
go minimal