11

我使用 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 文档吗?

4

1 回答 1

22

这是embeds_manyMongoid.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
于 2011-02-27T08:06:34.967 回答