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?

On Oct 29, 3:31 pm, et [email protected] wrote:

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

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

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

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.
#
# class Asset < ActiveRecord::Base
# belongs_to :attachable, :polymorphic => true
#
# def attachable_type=(sType)
# super(sType.to_s.classify.constantize.base_class.to_s)
# end
# end
#
# class Post < ActiveRecord::Base
# # because we store “Post” in attachable_type now :dependent
=> :destroy will work
# has_many :assets, :as => :attachable, :dependent => :destroy
# end
#
# class GuestPost < Post
# end
#
# class MemberPost < Post
# end
#