STI和多晶型 [英] STI and polymorphs

查看:103
本文介绍了STI和多晶型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,我的code

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

和尝试的旅途中得到的意见对一些NewsArticle我看到在日志中像

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

奇怪的是,commentable_type=邮报。 怎么了?

PS:Rails的2.3.5和放大器;&安培;红宝石1.8.7(2010-01-10补丁级别249)的i686-darwin10]

PS: Rails 2.3.5 && ruby 1.8.7 (2010-01-10 patchlevel 249) [i686-darwin10]

推荐答案

commentable_type 字段需要存储包含数据,一旦该行是由右表装表的名称,继承的类型将在键入列的文章表中加载。

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.

所以:

下面的注释指向它评论在桌子上。该职位表,身份证1

Here the comment points to the table that it comments on. The posts table, 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。

Then to load the NewsArticle, id 1 is loaded from posts, and the type there indicates a 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那就要看看类来确定表。这样,它可以只是看表之忧而忧的类型,一旦它到达那里。

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.

这篇关于STI和多晶型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆