2013-04-26 31 views
4

這裏是我的班記錄:提取所有相關的記錄有屬性

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
end 

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

類別有visible booloean。

我需要在Product中創建一個範圍,以便我可以獲得所有類別都是可見的產品(即:如果產品有10個類別,並且即使一個類別的產品設置爲false,範圍也應該丟棄產品)。

ActiveRecord調用和MySQL查詢都可以接受。

編輯:我們有成千上萬的產品,我們需要將這個操作委託給數據庫,因爲我們必須對這個數組產品進行分頁排序。

回答

0

你可以嘗試找出所有產品有:可見爲false.Then減去所有產品。 Product.all - Product.where('categories.visible=?', false).includes(:category)

+0

謝謝。 我想知道,是不是將該數組減法委託給Ruby?我們有數十萬種產品。例如,這樣的計算可能會是一場災難,因爲我們需要對其進行分頁。 – amencarini 2013-04-26 10:14:00

1
Product.where("id not in (select product_id from categories where visible='false')") 

希望這有助於。

+0

謝謝,但它不起作用:首先,'categories'沒有'category_id'列;其次,如果產品的ID爲2,而類別的可見性設置爲false且ID爲2,即使產品與該類別無關,也會被排除。 – amencarini 2013-05-26 12:21:52

相關問題