【发布时间】:2013-11-08 18:02:29
【问题描述】:
在 Rails 应用程序中,我使用 FactoryGirl 来定义一个通用工厂以及几个更具体的特征。一般情况和除一个特征之外的所有特征都有特定的关联,但我想定义一个特征,其中没有创建/构建该关联。我可以使用after 回调将关联的id 设置为nil,但这并不会从一开始就阻止关联记录的创建。
在 trait 定义中是否有办法完全禁止创建/构建已为 trait 所属的工厂定义的关联?
例如:
FactoryGirl.define do
factory :foo do
attribute "value"
association :bar
trait :one do
# This has the bar association
end
trait :two do
association :bar, turn_off_somehow: true
# foos created with trait :two will have bar_id = nil
# and an associated bar will never be created
end
end
end
【问题讨论】:
-
嗯,不确定我是否理解正确。你是说你在使用FactoryGirl创建模型实例的时候,要禁止Rails在创建模型实例的时候调用创建其他关联模型实例的回调??
-
@dmtri.com:我添加了一个示例,这有助于解释我想要做什么吗?
标签: ruby-on-rails associations factory-bot traits