2013-01-02 204 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