我使用Mongoid和Fabrication宝石。我从beta20切换到Mongoid.rc7,现在我无法用嵌入文档制作文档:
#Models
class User
include Mongoid::Document
embeds_many :roles
end
class Role
include Mongoid::Document
field :name, :type => String
embedded_in :user, :inverse_of => :roles
end
#Fabricators
Fabricator(:role) do
name { "role" }
end
Fabricator(:user) do
email { Faker::Internet.email }
password { "password" }
password_confirmation { |user| user.password }
roles { [] }
end
Fabricator(:admin_user, :from => :user) do
roles(:count => 1) { |user| Fabricate(:role, :user => user, :name => "admin") }
end
当我尝试制作admin_user
时,我会让用户没有角色。当我尝试制作角色时,我收到了错误。
#<User _id: 4d62a2fd1d41c87f09000003, email: "will@cole.com", encrypted_password: "$2a$10$r9I0Aeu5KPVKqq2rHRl3nuYpvohlB2XdrH6nB/K8XL21pCEHt8l6u", remember_created_at: nil, reset_password_token: nil, failed_attempts: 0, unlock_token: nil, locked_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>
>>u.roles
[]
>>r = Fabricate(:role)
Mongoid::Errors::InvalidCollection: Access to the collection for Role is not allowed since it is an embedded document, please access a collection from the root document.
使用Mongoid.beta20,这正如我所料。 有没有人知道如何使用Fabrication来制作带有嵌入文档的Mongoid.rc7文档?
答案 0 :(得分:22)
这是embeds_many
使用Mongoid.rc7的工作解决方案:
Fabricator(:admin_user, :from => :user) do
after_create { |user | user.roles << Fabricate.build(:role, :name => "admin") }
end
对于embeds_one
,此代码有效(地址嵌入一个位置):
Fabricator(:address) do
location { |address| Fabricate(:location, :address => address) }
end