Reputation: 1703
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
Upvotes: 3
Views: 640
Reputation: 2610
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
Upvotes: 2
Reputation: 17828
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:
Upvotes: 1