具有在线验证的深层嵌套关联工厂

时间:2015-03-29 20:42:16

标签: ruby-on-rails associations factory-bot

存在模型关系,因此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.

有没有简单/正确的方法来处理这个问题?

1 个答案:

答案 0 :(得分:0)

您无法从工厂创建Location,因为它是只读的#34;有一个通过"协会。您需要创建Relationship记录(使用location)。然后,您的car创作就可以了。

<强>更新

为了让汽车工厂照常运作create(:car),您可以在relationship定义中定义location before(:create)作为Factory回调的创建。更多信息,请Factory Girl - Callbacks