0

我的模型是:(使用 mongoid 版本2)

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.

我该如何解决?

4

3 回答 3

2

尝试以下查询,我希望它应该工作:

Trip.all.or(:images.size => 0).or(:images => nil)
于 2012-05-31T17:14:36.977 回答
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
于 2012-05-31T19:52:52.120 回答
1

只需添加我的解决方案,这可能会有所帮助(也是最新的语法):

scope :without_images, -> { any_of(:images.with_size => 0, images: nil) }
于 2015-06-04T16:05:15.137 回答