Ruby 在Mongoid中使用几个过滤器进行过滤

Ruby 在Mongoid中使用几个过滤器进行过滤,ruby,mongodb,mongoid,Ruby,Mongodb,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 conditi

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

 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类对象开始,然后链接调用并检查类,从而使代码干涸。 我使用数组重构参数,并在参数数组上迭代以使代码干涸。 我更喜欢使用“in”方法

希望这能为您提供一些关于更干净或更干燥的代码的有趣想法

app/model/item.rb

class Item
  include Mongoid::Document
  field :condition1, type: Integer
  field :condition2, type: Integer
  field :condition3, type: Integer
end
测试/单元/项目_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
需要“测试助手”
类ItemTest条件ID)如果条件ID&&!条件_id.empty?
结束
结果=items.class==Mongoid::条件?项目a:无
p结果
结束
结束
耙试验

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
运行选项:
#运行测试:
[#, #]
.
以0.010446s、95.7304次测试/秒、0.0000次断言/秒的速度完成测试。
1个测试,0个断言,0个失败,0个错误,0个跳过