我有Tag
型号:
class Tag
include Mongoid::Document
embedded_in :taggable, :polymorphic => true
key :title
field :title, :type => String
end
在此模型为embedded_in
之前,让key :title
强制ID基于标题。由于某种原因,它已经被嵌入,所以id会回到像4fb42e1f5d9a1e68f100000d
这样的东西。任何想法如何使密钥基于标题?
答案 0 :(得分:1)
我可以使用您指定的内容完全按键指定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