Ruby on rails 3 如何使用制作工具制作带有嵌入式文档的Mongoid文档?
我使用Mongoid和gems。我已从beta20切换到Mongoid.rc7,现在我无法使用嵌入的文档制作文档:Ruby on rails 3 如何使用制作工具制作带有嵌入式文档的Mongoid文档?,ruby-on-rails-3,mongoid,fabrication-gem,Ruby On Rails 3,Mongoid,Fabrication Gem,我使用Mongoid和gems。我已从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
#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\u 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.
#
>>u、 角色
[]
>>r=制造(:角色)
Mongoid::Errors::InvalidCollection:不允许访问角色的集合,因为它是嵌入文档,请从根文档访问集合。
对于Mongoid.beta20,这正如我预期的那样起作用。
是否有人知道如何使用制作制作嵌入文档制作Mongoid.rc7文档?这是一个针对使用Mongoid.rc7嵌入许多文件的工作解决方案:
Fabricator(:admin_user, :from => :user) do
after_create { |user | user.roles << Fabricate.build(:role, :name => "admin") }
end
您现在可以使用
制造商中的build
与您的代表一起标记制造:)build
是我让制造商正确保存嵌入(cascade\u回调:true))的关键。谢谢您的回答。但是,在创建后使用而不是是一种更好的方法。当调用manufacture.build(:admin\u user)
时,它填充address
,而之后的
则没有。发现如果我没有使用manufacture.build
,则在尝试持久化它时,我从“母亲”对象(在本例中为admin\u用户)获得了一些验证错误。不知道为什么?
Fabricator(:address) do
location { |address| Fabricate(:location, :address => address) }
end