如何使用Fabrication制作带有嵌入式文档的Mongoid文档? [英] How to fabricate Mongoid document with embedded document using Fabrication?
问题描述
我使用Mongoid和制造宝石.我已经从beta20切换到Mongoid.rc7,现在无法使用嵌入式文档来制作文档:
I use Mongoid and Fabrication gems. I have switched to Mongoid.rc7 from beta20 and now I can't fabricate document with embedded document:
#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
时,我得到的用户没有角色.当我尝试捏造角色时,出现错误.
When I try to fabricate admin_user
I get user without roles. When I try to fabricate role, I get an error.
#<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文档吗?
With Mongoid.beta20 this worked as I expected. Does anybody know how to fabricate Mongoid.rc7 document with embedded document using Fabrication?
推荐答案
这是使用Mongoid.rc7的embeds_many
的可行解决方案:
This is a working solution for embeds_many
with Mongoid.rc7:
Fabricator(:admin_user, :from => :user) do
after_create { |user | user.roles << Fabricate.build(:role, :name => "admin") }
end
对于embeds_one
,此代码有效(地址嵌入一个位置):
For embeds_one
this code works (address embeds one location):
Fabricator(:address) do
location { |address| Fabricate(:location, :address => address) }
end
这篇关于如何使用Fabrication制作带有嵌入式文档的Mongoid文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!