How to fabricate Mongoid document with embedded document using Fabrication?

狂风中的少年 提交于 2019-12-03 07:30:02

问题


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

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.

With Mongoid.beta20 this worked as I expected. Does anybody know how to fabricate Mongoid.rc7 document with embedded document using Fabrication?


回答1:


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

For embeds_one this code works (address embeds one location):

Fabricator(:address) do
  location { |address| Fabricate(:location, :address => address) }
end


来源:https://stackoverflow.com/questions/5069315/how-to-fabricate-mongoid-document-with-embedded-document-using-fabrication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!