關係方法類返回一個數組,而不是您的基類。 要創建並嵌入對象,您需要調用新的方法,然後將 添加到類。
下面是一個可能接近你想要的工作示例。希望它能幫助你繼續前進。
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
能否請您給您的模型結構。 – abhas
'Mongoid 2.0.0.beta.20'嚴重嗎?這個分支的最新版本是2.0.2。先嚐試升級。 –