添加一个新的关联
published_pages(除了当前的关联之外)
class Category has_many :children, :class_name => "Category", :foreign_key => "parent_id" has_many :published_pages, :class_name => "Page", :conditions => { :is_published => true }end现在,您可以获取所有类别,如下所示:
self.categories.includes(:children, :published_pages)
如果您有兴趣了解为什么您的方法行不通,请阅读Rails
文档(在本
Eagerloading of associations节后滚动10-15行)。我在下面列出了相关的代码段:
例如
Post.includes([:author, :comments]).where(['comments.approved = ?',true]).all
这将导致单个SQL查询的连接符合以下内容:
LEFT OUTER JOIN comments ON comments.post_id = posts.id andLEFT OUTER JOIN authors ON authors.id = posts.author_id.请注意,使用这样的条件可能会产生意想不到的后果。在上面的示例中,根本没有返回带有概念批准的注释的帖子,因为这些条件不仅适用于整个SQL语句,而且还适用于整个SQL语句。您必须消除列引用的歧义,以使此后备发生,例如::order
=>“ author.name DESC”将起作用,但:order =>“ name DESC”将不起作用。
要渴望加载关联的过滤行,请对条件使用关联:
class Post < ActiveRecord::base has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]endPost.find(:all, :include => :approved_comments)



