我需要一些帮助来正确设置我的 factory_girl 设置,其中包含嵌套属性。以下是三个模型供参考。
位置.rb
class Location < ActiveRecord::Base
has_many :person_locations
has_many :people, through: :person_locations
end
person_location.rb
class PersonLocation < ActiveRecord::Base
belongs_to :person
belongs_to :location
accepts_nested_attributes_for :location, reject_if: :all_blank
end
人.rb
class Person < ActiveRecord::Base
has_many :person_locations
has_many :locations, through: :person_locations
accepts_nested_attributes_for :person_locations, reject_if: :all_blank
end
请注意,位置嵌套在人员记录下,但需要经过两个模型才能嵌套。我可以让测试像这样工作:
it "creates the objects and can be called via rails syntax" do
Location.all.count.should == 0
@person = FactoryGirl.create(:person)
@location = FactoryGirl.create(:location)
@person_location = FactoryGirl.create(:person_location, person: @person, location: @location)
@person.locations.count.should == 1
@location.people.count.should == 1
Location.all.count.should == 1
end
我应该能够在一行中创建所有这三个记录,但还没有弄清楚如何去做。这是我希望正常工作的结构:
factory :person do
...
trait :location_1 do
person_locations_attributes { location_attributes { FactoryGirl.attributes_for(:location, :location_1) } }
end
end
我有其他模型可以通过类似的语法创建,但它只有一个嵌套属性,而不是更深的嵌套。
如上所述,我收到以下错误:
FactoryGirl.create(:person, :location_1)
undefined method `location_attributes' for #<FactoryGirl::SyntaxRunner:0x007fd65102a380>
此外,我希望能够正确测试我的控制器设置,以创建具有嵌套位置的新用户。如果我不能把电话接到一条线上,这将很难做到。
谢谢你的帮助!!希望我在上面提供了足够的内容来帮助其他人,当他们创建一个与嵌套属性有很多的关系时。