0

我有一些过滤条件应该应用于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

代码看起来不太好。有没有更有效的方法来做到这一点?

4

1 回答 1

0

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

希望这能给你一些关于更清洁或更干燥代码的有趣想法。

应用程序/模型/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
于 2013-01-05T05:02:21.500 回答