加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – STI和多形体

发布时间:2020-12-16 22:16:31 所属栏目:百科 来源:网络整理
导读:我的代码有问题 class Post ActiveRecord::Baseendclass NewsArticle Post has_many :comments,:as = :commentable,:dependent = :destroy,:order = 'created_at'endclass Comment ActiveRecord::Base belongs_to :commentable,:polymorphic = true,:counter
我的代码有问题
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”,则必须查看该类来确定该表.这样,它可以只是看着表,并担心类型一旦到达那里.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读