我可以用你指定的键获得指定的 id,确切地说。也许您对未共享的封装模型有问题?以下适用于 Ruby 1.9.3、Rails 3.2.3、Mongoid 2.4.9。
class Item
include Mongoid::Document
embeds_many :tags, as: :taggable
key :name
field :name, :type => String
end
测试/单元/tag_test.rb
require 'test_helper'
class TagTest < ActiveSupport::TestCase
def setup
Item.delete_all
#Tag.delete_all
end
test "key title" do
item = Item.create(name: 'book')
assert_equal(1, Item.count)
assert_equal('book', Item.where(name: 'book').first[:_id])
tag = Tag.new(title: 'scifi')
item.tags << tag
assert_equal('scifi', Item.where(name: 'book').first.tags.first[:_id])
puts Item.all.to_a.first.to_json
end
end
测试输出
Run options: --name=test_key_title
# Running tests:
{"_id":"book","name":"book","tags":[{"_id":"scifi","title":"scifi"}]}
.
Finished tests in 0.010775s, 92.8074 tests/s, 278.4223 assertions/s.
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips