使用factorygirls模型embeds_many和embedded_in关系

问题描述 投票:0回答:1

我想写FactoryGirl类来创建公司。模型如下:

module Company
  class Contact
    include Mongoid::Document
    include ActiveModel::Validations

    embedded_in :company, class_name: "::Company::Contact"

  end
end

module Company
  class Company

    require 'autoinc'

    embeds_many :contacts, class_name: "::Company::Contact"

  end
end


FactoryGirl.define do
  factory :company, :class => 'Company::Company' do
    name { Faker::Company.name }

    after(:create) do |company|
      # company.contacts << create(:company_contact)
      create_list(:company_contact, 1, company: company)
    end
    # contacts { [ build(:company_contact) ] }
  end
end

收到的错误是

失败/错误:create_list(:company_contact,1,company:company)

 Mongoid::Errors::InvalidPath:

   message:
     Having a root path assigned for Company::Contact is invalid.
   summary:
     Mongoid has two different path objects for determining the location of a document in the database, Root and Embedded. This error is raised when an embedded document somehow gets a root path assigned.
   resolution:
     Most likely your embedded model, Company::Contact is also referenced via a has_many from a root document in another collection. Double check the relation definitions and fix any instances where embedded documents are improperly referenced from other collections

我该怎么处理?我无法改变模型。

ruby-on-rails ruby testing mongoid rspec-rails
1个回答
0
投票

您的关联类名称错误:

module Company
  class Contact
    include Mongoid::Document
    include ActiveModel::Validations

    embedded_in :company, class_name: 'Company::Company'
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.