ActiveRecord的 - 查询多态关联多态、ActiveRecord

2023-09-08 15:50:24 作者:不爱就滚蛋

我使用多态关联,跟踪我的项目注释。一切都非常简单的东西。

I am using polymorphic associations to track Comments in my project. All very straight forward stuff.

我的问题是在查询基础上,多态关联,并从评价模型回到它的主人加入。

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

和一个ForumTopics方式:

And a ForumTopics mode:

class ForumTopic < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

我有几个其他的commentable模式,并不重要,现在。 所有这些工作的。

I have several other "commentable" models that aren't important right now. All of this works.

我所试图做的是找到所有属于ForumTopic与指定条件的意见(在这种情况下,'特色'==真)。

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] 
            )

我收到以下错误:

I receive the following error:

不能急于加载多态性关联:commentable 的

使用AR有语法:

@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的::错误:未知的表格'评论':选择意见的自评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