Ale*_*sev 10 activerecord ruby-on-rails single-table-inheritance polymorphic-associations
我的代码有问题
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
Run Code Online (Sandbox Code Playgroud)
并尝试去获取一些NewsArticle的评论,我在日志中看到类似的东西
Comment Load (0.9ms) SELECT "comments".* FROM "comments" WHERE ("comments"."commentable_id" = 1 and "comments"."commentable_type" = 'Post') ORDER BY created_at
Run Code Online (Sandbox Code Playgroud)
奇怪的是"commentable_type"="发布".怎么了?
PS:Rails 2.3.5 && ruby 1.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">
Run Code Online (Sandbox Code Playgroud)
然后加载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"
Run Code Online (Sandbox Code Playgroud)
如果持有commentable_type,"NewsArticle"则必须查看该类以确定该表.通过这种方式,它可以只看到桌子,并在它到达那里后担心类型.
| 归档时间: |
|
| 查看次数: |
1634 次 |
| 最近记录: |