[英]FactoryGirl belongs_to association and validates_presence_of failing — foreign key is associated, object is not
After upgrading from FactoryGirl 2.5.2 to 4.5.0, validations for belongs_to
associations fail. 从FactoryGirl 2.5.2升级到4.5.0后, belongs_to
关联的验证失败。
The two model files: 两个模型文件:
class User < ActiveRecord::Base
...
has_many :things
...
end
class Thing < ActiveRecord::Base
...
belongs_to :user
validates_presence_of :user
...
end
The factory: 该工厂:
FactoryGirl.define
factory :thing do
association :user
...
end
end
Creating a new thing
always fails saying User must be provided
. 创建新thing
总是失败,说User must be provided
。 When I step into the code, the problem is that the foreign key is set correctly, but the associated object appears to be nil. 当我进入代码时,问题是外键设置正确,但关联的对象似乎是零。
>> user = create(:user)
( returns saved "user" object )
>> user.id
1
>> thing = build(:thing, user: user)
( returns new "thing" object )
>> thing.valid?
false
>> thing.user_id
1
>> User.find(1).present?
true
>> thing.user
nil
I've tried all sorts of combinations and variations on this. 我已经尝试过各种各样的组合和变体。 I've tried using after(:build)
blocks to set the user and using different FactoryGirl syntax. 我尝试使用after(:build)
块来设置用户并使用不同的FactoryGirl语法。 I've tried just having a plain user
instead of the association. 我试过让普通user
而不是关联。 But it always comes down to this problem -- there is an associated key, and it is correct, but not an associated object (even though that object exists and is saved). 但它总是归结为这个问题 - 有一个关联的键,它是正确的,但不是一个关联的对象(即使该对象存在并被保存)。
Environment: 环境:
ruby 2.1.5
factory_girl 4.5.0
factory_girl_rails 4.5.0
rails 4.2.0
rspec 3.1.0
You need to define a User factory. 您需要定义用户工厂。 If you have done so, please edit your answer to show it. 如果您已经这样做,请编辑您的答案以显示它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.