0

my model is:(with mongoid version2)

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

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

i can search out entries, which its images size is not 0 by:

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

while this method can not used for searching blank array field:

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

how can i fix it?

3 Answers 3

2

Try the following query, I hope it should work:

Trip.all.or(:images.size => 0).or(:images => nil)
Sign up to request clarification or add additional context in comments.

Comments

1

The following test verifies that the latest edit by @rubish works.

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

test output

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

Comments

1

Just adding my solution which may be helpful (latest syntax as well):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.