ActiveRecord - 查询多态关联 [英] ActiveRecord - querying polymorphic associations
问题描述
我正在使用多态关联来跟踪我项目中的评论.所有非常简单的东西.
I am using polymorphic associations to track Comments in my project. All very straight forward stuff.
我遇到的问题是基于多态关联进行查询,并从 Comment 模型返回到它的所有者.
The problem I have is in querying based on the polymorphic association and joining from the Comment model back to it's owner.
所以……
我有一个评论模型
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
还有一个论坛主题模式:
And a ForumTopics mode:
class ForumTopic < ActiveRecord::Base
has_many :comments, :as => :commentable
end
我还有其他几个可评论"的模型,它们现在并不重要.所有这些都有效.
I have several other "commentable" models that aren't important right now. All of this works.
我想要做的是找到属于具有指定条件的 ForumTopic 的所有评论(在本例中,'featured' == true).
What I am trying to do is find all of the Comments that belong to a ForumTopic with a specified condition (in this case, 'featured' == true).
当我尝试使用查找器加入模型时:
When I try and use a finder to join the models:
@comments = Comment.find(:all
:joins => :commentable
:conditions => ["forum_topics.featured = ? ", true]
)
我收到以下错误:
不能急切地加载多态关联:commentable
使用 AR包含语法":
Using the AR "include syntax":
@comments = Comment.find(:all
:include => :forum_topics
:conditions => ["forum_topics.featured = ? ", true]
)
返回:
未找到名为forum_topics"的关联;也许你拼错了?
如果我尝试使用表名而不是关联名(字符串而不是符号)加入:
If I try and join with a table name instead of the association name (string instead of symbol):
@comments = Comment.find(:all,
:joins => "forum_topics",
:conditions => ["forum_topics.featured = ? ", true]
)
我明白了:
Mysql::Error: Unknown table 'comments': SELECT comments. FROM comments forum_topics WHERE (forum_topics.featured = 1 )*
Mysql::Error: Unknown table 'comments': SELECT comments. FROM comments forum_topics WHERE (forum_topics.featured = 1 )*
(您可以在此处看到底层查询的语法完全关闭,并且完全没有连接).
(You can see here that the syntax of the underlying query is totally off and the join is missing altogether).
不确定我正在做的事情是否可行,还有其他方法可以实现所需的结果,但看起来应该是可行的.
Not sure if what I am doing is even possible, and there are other ways to achieve the required result but it seems like it should be doable.
有什么想法吗?我有什么遗漏吗?
Any ideas? Anything I am missing?
推荐答案
啊!
我想我发现了问题.
通过以下方式加入时:
@comments = Comment.find(:all,
:joins => "forum_topics",
:conditions => ["forum_topics.featured = ? ", true]
)
你需要整个加入!
:joins => "INNER JOIN forum_topics ON forum_topics.id = comments.commentable_id",
看到令人敬畏的:http://guides.rubyonrails.org/active_record_querying.html#joining-tables
这篇关于ActiveRecord - 查询多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!