0

我有一个Tag模型:

class Tag
  include Mongoid::Document

  embedded_in :taggable, :polymorphic => true

  key :title
  field :title, :type => String
end

在此模型之前embedded_inkey :title强制 id 基于标题。由于某种原因,现在它被嵌入了,id 又回到了4fb42e1f5d9a1e68f100000d. 任何想法如何让密钥基于标题?

4

1 回答 1

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
于 2012-05-17T19:33:32.153 回答