2011-01-07 6 views
2

productsActiveRecord::Relationです。Rails 3: "ActiveRecord :: Relation"の項目をフィルタリングする方法は?

filtered_products.order(...) 

しかしfiltered_productsではないので、私はこれを行うことはできません。

def my_filter(products) 
    last_brand_id = last_model_id = nil 
    filtered_products = [] 

    products.each do |product| 
    filtered_products << product if (product.model.brand_id != last_brand_id) || (product.model_id != last_model_id) 

    last_brand_id = product.model.brand_id 
    last_model_id = product.model_id 
    end 

    filtered_products 
end 

は、今私がフィルタリング製品を注文したい

filtered_products = my_filter(products) 

:Iこのようないくつかの製品をフィルタリングActiveRecord::Relation

my_filterを書き換えるにはどうすればActiveRecord::Relationを返すべきですか。

または、より良い解決策がありますか?

+0

これは、ifが何であるかによって異なります - これはデータベースからのみアクセス可能な条件であり、ルビコードからt? –

+0

私は質問を更新しました。これで、if条件を見ることができます。 –

答えて

0

あなたのオブジェクトを保持するように、あなたの 'my​​_filter'メソッドをクラスメソッドまたはスコープに変換することをお勧めします。

EDIT 1:あなたのフィルタ機能を宣言し、

まず:

def my_filter(product) 
    @last_brand_id ||= nil 
    @last_model_id ||= nil 
    test = (product.model.brand_id != last_brand_id || product.model_id != last_model_id) 
    @last_brand_id = product.model.brand_id 
    @last_model_id = product.model_id 
    test 
end 

は、その後、あなたが望む製品をフェッチ:

filtered_products = products.select{|p| p if my_filter(p)} 

のはあなたに広いソリューションを提供してみましょう

+0

どうすればいいですか? (私は質問を更新しました) –

+0

私は混乱しています: 'products.each do | product |'正しい場所で?もう一度ループする前にlast_brand_idとlast_model_idを更新しないでください。 – apneadiving

+0

あなたは正しいです。私はそれを修正した。 –

関連する問題