0

私のモデルは次のとおりです:(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.

どうすれば修正できますか?

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)

test / unit / 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 に答える