开发者

ActiveRecord, has_many, polymorphic and STI

I've came into a problem while working with AR and polymorphic, here's the description,

class Base < ActiveRecord::Base; end

class Subscription < Base

set_table_name :subscriptions

has_many :post开发者_如何学JAVAs, :as => :subscriptable

end

class Post < ActiveRecord::Base

belongs_to :subscriptable, :polymorphic => true

end

in the console,

>> s = Subscription.create(:name => 'test')

>> s.posts.create(:name => 'foo', :body => 'bar')

and it created a Post like:

#<Post id: 1, name: "foo", body: "bar", subscriptable_type: "Base", subscriptable_id: 1, created_at: "2010-05-10 12:30:10", updated_at: "2010-05-10 12:30:10">

the subscriptable_type is Base but Subscription, anybody can give me a hand on this?


If the class Base is an abstract model, you have to specify that in the model definition:

class Base < ActiveRecord::Base
  self.abstract_class = true 
end 


Does your subscriptions table have a 'type' column? I'm guessing that Rails thinks that Base/Subscription are STI models. So when a row is retrieved from the subscriptions table and no 'type' column is present, it just defaults to the parent class of Base. Just a guess...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜