如何通过mongoid查询带有空白数组字段的条目?

时间:2012-05-31 06:28:03

标签: arrays mongoid

我的模型是:(使用mongoid version2)

class Trip
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes

  field :images, :type => Array, :default => []
end

我可以搜索出条目,其图像大小不是0:

Trip.where(:images.size => 1).size #=>1, correct

虽然此方法不能用于搜索空白数组字段:

Trip.where(:images.size => 0).size #=>0, error, as i do have many entries with default [] field.

我该如何解决?

3 个答案:

答案 0 :(得分:2)

尝试以下查询,我希望它应该有效:

Trip.all.or(:images.size => 0).or(:images => nil)

答案 1 :(得分:1)

以下测试验证@rubish的最新编辑是否有效。

Trip.all.or(:images.size => 0).or(:images => nil)

测试/单元/ trip_test.rb

require 'test_helper'

class TripTest < ActiveSupport::TestCase
  def setup
    Trip.delete_all
  end

  test "criteria or" do
    Trip.create(:images => nil)
    Trip.create(:images => [])
    Trip.create(:images => ['xyzzy'])
    assert_equal(3, Trip.count)
    puts "Trip.all images:#{Trip.all.to_a.map(&:images).inspect}"
    trips_with_images_empty_or_nil = Trip.all.or(:images.size => 0).or(:images => nil).to_a
    puts "trips_with_images_empty_or_nil images: #{trips_with_images_empty_or_nil.map(&:images).inspect}"
    assert_equal(2, trips_with_images_empty_or_nil.size)
  end
end

测试输出

Run options: --name=test_criteria_or

# Running tests:

Trip.all images:[nil, [], ["xyzzy"]]
trips_with_images_empty_or_nil images: [nil, []]
.

Finished tests in 0.009099s, 109.9022 tests/s, 219.8044 assertions/s.

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

答案 2 :(得分:1)

只需添加可能有用的解决方案(最新语法):

scope :without_images, -> { any_of(:images.with_size => 0, images: nil) }