存在模型关系,因此Car
有一个Location
到2个嵌套模型。
class Car
has_one :owner
has_one :relationships, through: :owner
has_one :location, through: :relationships
validation :location, presence: true
end
我需要为Car
创建一个工厂,所以我这样做了:
FactoryGirl.define do
factory :car do
location
end
end
但create(:car)
引发HasManyThroughNestedAssociationsAreReadonly
例外:
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly:
Cannot modify association 'Car#location' because it goes through more than one other association.
有没有简单/正确的方法来处理这个问题?
答案 0 :(得分:0)
您无法从工厂创建Location
,因为它是只读的#34;有一个通过"协会。您需要创建Relationship
记录(使用location
)。然后,您的car
创作就可以了。
<强>更新强>
为了让汽车工厂照常运作create(:car)
,您可以在relationship
定义中定义location
before(:create)
作为Factory
回调的创建。更多信息,请Factory Girl - Callbacks