2013-01-02 260 views
0

我有,應適用於Item模型過濾通過一些過濾器Mongoid

condition1_ids = get_condition1_ids # array of ids 
condition2_ids = get_condition2_ids # array of ids 
condition3_ids = get_condition3_ids # array of ids 

items = Item.where(:condition1.in => condition1_ids) if condition1_ids 
items = items ? 
      (items.where(:condition2.in => condition2_ids) if condition2_ids) : 
      (Item.where(:condition2.in => condition2_ids) if condition2_ids) 

items = items ? 
      (items.where(:condition3.in => condition3_ids) if condition3_ids) : 
      (Item.where(:condition3.in => condition3_ids) if condition3_ids) 

的想法是由每個過濾器如果過濾器設置(AND條件)來過濾Item模型的一些過濾條件。

代碼不好看。有沒有更有效的方法來做到這一點?

回答

0

以下工作的測試代碼包含了你一些建議。 您可以通過與項目類對象開始幹你的代碼,然後鏈中的呼叫和檢查類。 我重構出使用在參數數組陣列和迭代至乾涸碼參數。 我更喜歡使用「入法」。

希望這給你的清潔劑或機代碼的一些有趣的想法。

應用程序/模型/ item.rb的

class Item 
    include Mongoid::Document 
    field :condition1, type: Integer 
    field :condition2, type: Integer 
    field :condition3, type: Integer 
end 

測試/單元/ item_test.rb

require 'test_helper' 

class ItemTest < ActiveSupport::TestCase 
    def setup 
    Item.delete_all 
    end 

    def get_condition1_ids; [1, 2]; end 
    def get_condition2_ids; [2, 3]; end 
    def get_condition3_ids; nil; end 

    test "criteria chain" do 
    Item.create(condition1: 1, condition2: 2, condition3: 3) 
    Item.create(condition1: 2, condition2: 3, condition3: 4) 
    Item.create(condition1: 3, condition2: 4, condition3: 5) 

    condition1_ids = get_condition1_ids # array of ids 
    condition2_ids = get_condition2_ids # array of ids 
    condition3_ids = get_condition3_ids # array of ids 

    items = Item 
    [ 
     [:condition1, condition1_ids], 
     [:condition2, condition2_ids], 
     [:condition3, condition3_ids] 
    ].each do |condition, condition_ids| 
     items = items.in(condition => condition_ids) if condition_ids && !condition_ids.empty? 
    end 

    result = items.class == Mongoid::Criteria ? items.to_a : nil 
    p result 
    end 
end 

耙測試

Run options: 

# Running tests: 

[#<Item _id: 50e7b11b29daebeefd000001, _type: nil, condition1: 1, condition2: 2, condition3: 3>, #<Item _id: 50e7b11b29daebeefd000002, _type: nil, condition1: 2, condition2: 3, condition3: 4>] 
. 

Finished tests in 0.010446s, 95.7304 tests/s, 0.0000 assertions/s. 

1 tests, 0 assertions, 0 failures, 0 errors, 0 skips