10

好吧,我完全被这个难住了。我正在尝试构建按类别组织的已发布网页的菜单。

类别.rb:

belongs_to :parent, :class_name => "Category", :foreign_key => "parent_id"
has_many   :children, :class_name => "Category", :foreign_key => "parent_id"
has_many :pages, :documents, :galleries

页面.rb

belongs_to :category

Page 模型也有 :is_published,所以我也在尝试过滤它。我不愿意发布我微弱的查询尝试,但除了乞求更聪明的人之外,没有其他解决方案:

(自己是@current_website)

self.categories.includes(:children, :pages).where('pages.is_published = 1')

这主要返回我需要的内容,但不是没有发布页面的父类别。例如,如果我有,它会很好:

Parent Category
- Published Page
- Child Category
-- Published Page

它失败的地方是我在父级中没有已发布的页面,如下所示:

Parent Category
- Child Category
-- Published Page
- Child Category
-- Published Page

提前感谢您对此的任何帮助。我正在尝试尽可能多地了解查询,但我在这方面遇到了困难。

更新:实施 KandadaBoggu 的建议产生了更好的结果,这被添加到 Category.rb

  has_many :published_pages, :class_name => "Page",
                             :conditions => {:is_published => true}

但是,当使用以下内容时:

self.categories.where(:parent_id => nil).includes({:children => :published_pages},
                                                   :published_pages)

我得到了我需要的结果,但我也得到了空的父类别(没有已发布的页面,没有带有已发布页面的子类别。例如:

- Parent Category
-- Published Page
- Parent Category
-- NOTHING

我的临时解决方法是在查询中附加:

reject{|category| category.pages.empty? && category.children.empty?}

再次感谢您的帮助。

4

1 回答 1

14

添加一个名为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文档(在该部分之后滚动 10-15 行Eager loading of associations)。我在下面包含了相关的片段:

例如

Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all

这将导致单个 SQL 查询的连接如下:

LEFT OUTER JOIN comments ON comments.post_id = posts.id and 
LEFT OUTER JOIN authors  ON authors.id = posts.author_id. 

请注意,使用这样的条件可能会产生意想不到的后果。在上面的示例中,根本不会返回带有已批准评论的帖子,因为条件适用于整个 SQL 语句,而不仅仅是关联。您必须消除列引用的歧义才能发生此回退,例如 :order => "author.name DESC" 将起作用,但 :order => "name DESC" 将不起作用。

要预先加载关联的过滤行,请使用带有条件的关联:

class Post < ActiveRecord::Base
  has_many :approved_comments, :class_name => 'Comment', 
             :conditions => ['approved = ?', true]
end

Post.find(:all, :include => :approved_comments)
于 2010-11-17T01:23:14.470 回答