以下适用于 Rails 3.2.13、Mongoid 3.1.4、Moped 1.5.0。
应用程序/模型/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
应用程序/模型/item.rb
class Item
include Mongoid::Document
field :name, type: String
has_and_belongs_to_many :users
end
测试/单元/user_test.rb
需要'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
User.delete_all
Item.delete_all
end
test "users without items" do
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
耙式试验
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
希望这会有所帮助。