mongodb - How to select all records where related collection is empty with Mongoid -
i'm still getting hang of mongodb , mongoid , have hit snag.
let's have user
has_and_belongs_to_many
items
, of course item
has_and_belongs_to_many
users
.
i'd able count users items.
this question recommended adding scope
tried adding scope user
such as
scope :has_no_items, where(:items.empty?)
but user.count - user.has_no_items.count
returns 0
.
i've looked @ .with_size
that's specific array fields.
what correct way other than
count = 0 user.each { |u| count += 1 unless u.items.empty? }
which works doesn't seem elegant.
how do efficiently?
the following works me rails 3.2.13, mongoid 3.1.4, moped 1.5.0.
app/models/user.rb
class user include mongoid::document field :name, type: string has_and_belongs_to_many :items scope :has_items, where(:item_ids.ne => nil) scope :has_no_items, where(:item_ids => nil) end
app/models/item.rb
class item include mongoid::document field :name, type: string has_and_belongs_to_many :users end
test/unit/user_test.rb
require 'test_helper'
class usertest < activesupport::testcase def setup user.delete_all item.delete_all end test "users without items" fagin = user.create(:name => 'fagin') oliver = user.create(:name => 'oliver') fagin.items << item.create(:name => 'cane') assert_equal 2, user.count assert_equal 1, item.count assert_equal 1, user.has_items.count assert_equal 1, user.has_no_items.count puts puts "user.has_items: #{user.has_items.to_a.inspect}" puts "user.has_no_items: #{user.has_no_items.to_a.inspect}" end end
rake test
run options: # running tests: [1/1] usertest#test_users_without_items user.has_items: [#<user _id: 51df00987f11ba3d7d000001, name: "fagin", item_ids: ["51df00987f11ba3d7d000003"]>] user.has_no_items: [#<user _id: 51df00987f11ba3d7d000002, name: "oliver", item_ids: nil>] finished tests in 0.042205s, 23.6939 tests/s, 94.7755 assertions/s. 1 tests, 4 assertions, 0 failures, 0 errors, 0 skips
hope helps.
Comments
Post a Comment