我的代码有问题
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
Comment Load (0.9ms) SELECT "comments".* FROM "comments" WHERE ("comments"."commentable_id" = 1 and "comments"."commentable_type" = 'Post') ORDER BY created_at
奇怪的是“commentable_type”=’Post’.
怎么了?
PS:Rails 2.3.5&&ruby1.8.7(2010-01-10 patchlevel 249)[i686-darwin10]
解决方法
commentable_type字段需要存储包含数据的表的名称,一旦从正确的表中加载该行,继承的类型将从帖子表的类型列中加载.
所以:
>> Comment.first => #<Comment id: 1,commentable_id: 1,commentable_type: "Post",body: "test",created_at: "2010-04-09 00:56:36",updated_at: "2010-04-09 00:56:36">
然后加载NewsArticle,id 1从帖子加载,类型在那里指示一个NewsArticle.
>> Comment.first.commentable => #<NewsArticle id: 1,type: "NewsArticle",name: "one",body: "body",created_at: "2010-04-09 00:55:35",updated_at: "2010-04-09 00:55:35"> >> Comment.first.commentable.class.table_name => "posts"
如果commentable_type持有“NewsArticle”,则必须查看该类来确定该表.这样,它可以只是看着表,并担心类型一旦到达那里.