0

関連付けを検証するオブジェクトとの標準的な has_many 関係があります。しかし、エラースタックレベルが深すぎるのを避ける方法はありません。

ここに私の2つのモデル

class Address < ActiveRecord::Base
 belongs_to :employee, :inverse_of => :addresses
end

class Employee < ActiveRecord::Base

  has_many :addresses, :dependent => :destroy, :inverse_of => :employee     #inverse of       can use addresses.employee
  has_many :typings
  has_many :types, through: :typings

  validates :addresses, length: { minimum: 1 }
  validates :types, length: { minimum: 1 }


end

ここに私の工場

FactoryGirl.define do
 factory :address, class: Address do
   address_line 'test'
   name 'Principal'
   city 'test'
   zip_code 'test'
   country 'france'
 end
end

FactoryGirl.define do
 factory :employee_with_address_type, class: Employee do |e|
   e.firstname   'Jeremy'
   e.lastname    'Pinhel'
   e.nationality 'France'
   e.promo       '2013'
   e.num_mobile  'Test'
   e.types { |t| [t.association(:type)] }
   after :build do |em|
    em.addresses << FactoryGirl.build(:address)
   end
 end
end

ここで私のモデルテスト

describe Address do
  context 'valid address' do
  let(:address) {FactoryGirl.build(:address)}
  subject {address}

  #before(:all) do
  #  @employee = FactoryGirl.build(:employee_with_address_type)
  #end

  it 'presence of all attributes' do
     should be_valid
  end
 end
end

誰かがこの問題を解決する方法を理解するのを手伝ってくれますか? 私は自分の工場でさまざまな組み合わせを試みましたが、成功しませんでした。

編集:

 class Employee < ActiveRecord::Base

  has_many :addresses, :dependent => :destroy, :inverse_of => :employee     #inverse of       can use addresses.employee
  has_many :typings
  has_many :types, through: :typings

  validates_associated :addresses
  validates_associated :types


 end
4

1 に答える 1

0

ファクトリを次のように書き換えることができます。

     FactoryGirl.define do
      factory :address_with_employee, class: Address do
        address_line 'test'
        name 'Principal'
        city 'test'
        zip_code 'test'
        country 'france'
        association :employee, :factory => :employee_with_address_type
        after :build do |ad|
          ad.employee.addresses << ad
        end
      end
     end

     FactoryGirl.define do
      factory :employee_with_address_type, class: Employee do |e|
        e.firstname   'Jeremy'
        e.lastname    'Pinhel'
        e.nationality 'France'
        e.promo       '2013'
        e.num_mobile  'Test'
        e.types { |t| [t.association(:type)] }
      end
     end

私がしたことは、作成された住所インスタンスを従業員の住所に直接追加することだけでした。このビルド後のループでは、もちろん、同じ従業員で追加の住所を作成し、それらをリストに追加することもできます。

于 2013-08-05T10:09:21.613 に答える