ruby-on-rails – STI和多形体

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – STI和多形体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码有问题
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字段需要存储包含数据的表的名称,一旦从正确的表中加载该行,继承的类型将从帖子表的类型列中加载.

所以:

这里的评论指向它的评论表.帖子表,id 1

>> 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”,则必须查看该类来确定该表.这样,它可以只是看着表,并担心类型一旦到达那里.

猜你在找的Ruby相关文章