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

Arrays 如何通过mongoid查询出具有空白数组字段的条目?,arrays,mongoid,Arrays,Mongoid,我的模型是:(使用mongoid版本2) 我可以通过以下方式搜索其图像大小不是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. 如何修复它?请尝试以下查询,我希望它能正常工作: T

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

我可以通过以下方式搜索其图像大小不是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.

如何修复它?

请尝试以下查询,我希望它能正常工作:

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

请尝试以下查询,我希望它能够正常工作:

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

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

Trip.all.or(:images.size => 0).or(:images => nil)
测试/装置/跳闸测试.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

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

Trip.all.or(:images.size => 0).or(:images => nil)
测试/装置/跳闸测试.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

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


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