关系方法类返回一个数组,而不是您的基类。要创建和嵌入对象,您需要在类上调用新方法,然后将其附加到classes。
这是一个可能与您的意图接近的工作示例。希望它可以帮助您继续前进。
class User
include Mongoid::Document
field :name, type: String
embeds_many :classes, class_name: 'MyClass'
end
class MyClass
include Mongoid::Document
field :name, type: String
embedded_in :user
end
测试/单元/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
User.delete_all
end
test "embedded doc" do
User.create(name: 'Gary')
assert_equal(1, User.count)
u = User.last
u.classes.destroy_all
puts "u.classes.class: #{u.classes.class}"
u.classes << MyClass.new(:name => 'Philosophy')
user = User.find(u.id)
assert_equal('Philosophy', user.classes.first.name)
puts user.to_json
end
end
测试输出
Run options: --name=test_embedded_doc
# Running tests:
u.classes.class: Array
{"_id":"4fc62aeb7f11baa5b0000001","classes":[{"_id":"4fc62aeb7f11baa5b0000002","name":"Philosophy"}],"name":"Gary"}
.
Finished tests in 0.009929s, 100.7151 tests/s, 201.4302 assertions/s.
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips