我在 FactoryGirl 中设置了一个非常简单的关联,但由于某种原因它不起作用。该应用程序适用于旅游公司,因此每个旅游都有一个目的地(我使用的是 ActiveRecord,因此 Tour
模型 belongs_to
是一个 Destination
- - 所有旅行都需要此关联)。所以我像这样建立了我的工厂:
# spec/factories.rb
FactoryGirl.define do
factory :destination do
name "Example Destination"
city "Example City"
state "CA"
end
factory :tour do
departure_date { 1.day.from_now }
return_date { 1.day.from_now }
destination
end
end
但是,当我调用 FactoryGirl.attributes_for(:tour)
时,它返回:
{:departure_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00,
:return_date => Mon, 04 Nov 2013 17:51:26 UTC +00:00}
没有destination_id
!为什么?
destination
工厂工作得很好。
我尝试以旧方式定义关联association :destination,factory: :destination
,但这没有帮助。如果我手动将 destination_id
定义为 destination_id FactoryGirl.create(:destination).id
,我可以让它工作,但我不必这样做。知道为什么它不起作用吗?
最佳答案
attributes_for
不会加载关联对象。它只为您请求的对象生成属性。
要让它加载关联的目标
,请改用build
或create
。
关于ruby-on-rails - 工厂女协会不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756198/