Polymorphic Associations with inheritance

I have two models, Article and Post, that has many Comments. However, both Article and Post are inherited from a BaseContent class like so:

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

Now when I try to associate a comment with an Article or Post, the commentable_type field gets set as "BaseContent" instead of "Article" or "Post." Is there a way to specify what the commentable_type field is?

Hi,

can you show how are you creating Post and Comment and "joining" them?

I'm just doing:

comment = Comment.New() # set comment properties here comment.save Post.comments << comment

Have you tried this way?

It worked for me:

comment = Comment.New() comment.commentable = post #instance of the actual post you are commenting # set comment properties here comment.save

That still saves the comment as commentable_id = 1, commentable_type = BaseContent.

So when I save a comment for Article with id 1 and another comment for Post with id 1, there now are two comments with commentable_id = 1, commentable_type = BaseContent and they both show up with I do Article.find(1).comments and Post.find(1).comments

I forgot about the problems with STI you would have to define commentable_type method in BaseContent as said in the: activerecord/lib/active_record/associations.rb

    # Using polymorphic associations in combination with single table inheritance (STI) is a little tricky. In order     # for the associations to work as expected, ensure that you store the base model for the STI models in the     # type column of the polymorphic association. To continue with the asset example above, suppose there are guest posts     # and member posts that use the posts table for STI. In this case, there must be a +type+ column in the posts table.