2011-07-25 146 views
3

複雜的搜索我有以下模式設置軌與祖先

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 - 系列。現在IM建立這種類型的搜索查詢與meta_search寶石

@products = (Product.search :watch_category_name_contains => params[:search]).all.paginate(:page => params[:page]) 

這個工程的幫助下,用serie_name返回所有產品。但是手錶總是隻包含2級分類(serie)的category_id,而im需要能夠通過make(1級分類)搜索產品。我如何構建這種類型的查詢?謝謝!

回答

0

那麼,我看到一些upvotes來我的老問題,所以我會回答。我使用原始的SQL完成製作和系列查詢。這裏是:

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 

希望這可以幫助別人。