过滤Mongoid中的一些过滤器

时间:2013-01-02 11:03:50

标签: ruby mongodb mongoid

我有一些过滤条件应该应用于Item模型

 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)

如果设置了过滤器(Item条件),我们的想法是按每个过滤器过滤AND模型。

代码看起来不太好。有没有更有效的方法呢?

1 个答案:

答案 0 :(得分:0)

以下工作测试代码包含一些建议。 您可以通过从Item类对象开始,然后链接您的调用并检查类来干扰您的代码。 我使用数组重构参数并将参数数组迭代到DRY-up代码。 我更喜欢使用“in”方法。

希望这能为您提供有关清洁剂或DRYer代码的一些有趣想法。

应用程序/模型/ 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

rake test

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