I have problem with my code
class Post < ActiveRecord::Base
end
class NewsArticle < Post
has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at'
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true, :counter_cache => true
end
And on attempt go get comments for some NewsArticle i see in logs something like
Comment Load (0.9ms) SELECT "comments".* FROM "comments" WHERE ("comments"."commentable_id" = 1 and "comments"."commentable_type" = 'Post') ORDER BY created_at
Strange that "commentable_type" = 'Post'. What's wrong?
PS: Rails 2.3.5 && ruby 1.8.7 (2010-01-10 patchlevel 249) [i686-darwin10]
def commentable_type=(sType) super(sType.to_s.classify.constantize.base_class.to_s) end
This method is returning class as Post, what to do if you want to store the inherited class Post as commentable_type?
Take a look at the Polymorphic Associations section of ActiveRecord::Associations API. There is a little bit about using polymorphic associations in combination with single table inheritance. Following the second code example in that section I think this might be close to what you want
The commentable_type field needs to store the name of the table that contains the data, once that row is loaded from the right table, the inherited type will be loaded from the type column on the Posts table.
So:
Here the comment points to the table that it comments on. The posts table, id 1
Then to load the NewsArticle, id 1 is loaded from posts, and the type there indicates a NewsArticle.
If commentable_type held
"NewsArticle"
it would have to look at the class to determine the table. This way it can just look to the table and worry about the type once it gets there.Good question. I had exactly the same problem using Rails 3.1. Looks the problem is not solved yet. Apparently, using polymorphic associations in combination with Single Table Inheritance (STI) in Rails is a bit complicated.
The current Rails documentation for Rails 3.2 gives this advice for combining polymorphic associations and STI:
In your case the base model would be "Post", i.e. "commentable_type" should be "Post" for all comments.
Technically, there's actually nothing wrong with this. When Rails is dealing with a polymorphic association, and the object being associated is using STI, it simply uses the base class as the type (in your case "commentable_type").
If you have Post and NewsArticle in separate tables, obviously the commentable_type will show up as Post and NewsArticle respectively.