轨道复杂的搜索与祖先

时间:2011-07-25 09:17:50

标签: ruby-on-rails database search activerecord

我有以下模型设置

class Category < ActiveRecord::Base

  has_ancestry :cache_depth => true, :depth_cache_column => :depth

  has_many :watches, :dependent => :destroy
  has_many :products, :through => :watches
end

class Watch < ActiveRecord::Base

  belongs_to :category
  has_many :products
end

class Product < ActiveRecord::Base

  belongs_to :watch, :counter_cache => true
  belongs_to :category
end

我需要通过类别名称查找产品。类别有2层深(树形结构)。 1 - 级别是制造,2 - 系列。现在我在meta_search gem

的帮助下构建这种类型的搜索查询
@products = (Product.search :watch_category_name_contains => params[:search]).all.paginate(:page => params[:page])

这可以使用serie_name返回所有产品。但是监视表总是只包含2级别(系列)的category_id,并且我需要能够通过make(1级别类别)搜索产品。我该如何构建这种类型的查询?谢谢!

1 个答案:

答案 0 :(得分:0)

好吧,我看到我的旧问题上有一些赞成,所以我会回答。我完成了原始sql的make和系列查询。这是:

  def self.makes_with_products
    find_by_sql "
SELECT makes.* FROM categories makes
WHERE ancestry IS NULL AND makes.id IN (
    SELECT series.ancestry FROM products p
    INNER JOIN watches w ON w.id = p.watch_id
    INNER JOIN categories series ON series.id = w.category_id
    WHERE series.ancestry = makes.id AND p.active
  )
"
  end

  def series_with_products
   find_by_sql "
SELECT series.* FROM categories series
WHERE series.ancestry = '#{id}'
  AND (
    SELECT COUNT(*) FROM products p
    INNER JOIN watches w ON w.id = p.watch_id
    WHERE w.category_id = series.id AND p.active
  ) > 0
"
  end

希望这有助于某人。