2012-05-31 44 views
0

我的模型是:(帶mongoid版本2)如何用mongoid查詢空白數組的字段?

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. 

我該如何解決它?

回答

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

嘗試下面的查詢,我希望它應該工作:

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

只是加入我的解決方案,它可以是有幫助的(最新的語法以及):

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