Associations not loading

纵饮孤独 提交于 2019-12-12 01:31:57

问题


So I seem to be having some difficulties with the has_many associations in Factory_Girl

I have four classes with associations:

  • Aaa has_many bbbs & cccs
  • Bbb belongs_to aaa & ddd
  • Ccc belongs_to aaa & ddd
  • Ddd has_many bbbs & cccs

Here are the classes

spec\factories\aaas.rb

FactoryGirl.define do
  factory :aaa do
  end
end

spec\factories\bbbs.rb

FactoryGirl.define do
  factory :bbb do
    aaa
    ddd
  end
end

spec\factories\cccs.rb

FactoryGirl.define do
  factory :ccc do
    aaa
    ddd
  end
end

spec\factories\ddds.rb

FactoryGirl.define do
  factory :ddd do
  end
end

Here's the test I am running

spec\models\aaa_spec.rb

require 'spec_helper'

describe Aaa do
  it "works" do
    aaa = FactoryGirl.create(:aaa)
    puts aaa
    puts aaa.bbbs # This shows up as [] 
    puts aaa.cccs # This shows up as []
    aaa.bbbs.each {|bbb| puts bbb.ddd} # This is nil 
    aaa.cccs.each {|ccc| puts ccc.ddd} # This is nil 
  end
end

Why isnt aaa.bbbs, aaa.cccs, or the ddds showing up?


回答1:


Reason is simple: in your factory you haven't created any bbb's or ccc's, so you're in the case of "0 objects" (which is a perfectly legal state of "has many"...

If you also want these objects to be created in your factory, you can add something like

after(:build) do |aaa, evaluator|
  aaa.bbb << build(:bbb)
  aaa.ccc << build(:ccc)
end

to your aaa factory




回答2:


aaas.rb

FactoryGirl.define do
  factory :aaa do
    after(:create) do |aaa|
      create_list(:bbb, 1, aaa: aaa)
      create_list(:ccc, 1, aaa: aaa)
    end
  end
end

Get rid of the aaa in bbbs.rb and cccs.rb

ddds.rb can remain as is.



来源:https://stackoverflow.com/questions/23237040/associations-not-loading

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