【问题标题】:FactoryGirl for models with inheritance where parent and child have associationsFactoryGirl 用于具有父子关系的继承模型
【发布时间】:2014-11-20 11:20:14
【问题描述】:

我有一个典型的继承模式,但是父级与另一个模型有关联,而子级也与其他模型有关联。

class MyBase < ActiveRecord::Base
  belongs_to :game, inverse_of: :my_base
  validates :game, presence: true
end

class Child < MyBase
  self.table_name = 'children'
  belongs_to :user, inverse_of: :child
  validates :user, presence: true
end

我知道我可以告诉工厂女孩使用特定的类,但是当我使用子类作为构造函数时,它无法为父类创建关联,反之亦然。

  factory :child, class: MyBase, parent: :my_base do
    association :user, strategy: :build
  end

这给了我 invalid factory 当 linted 时:

child - can't write unknown attribute 'user_id' (ActiveModel::MissingAttributeError)

我需要如何设置我的工厂以创建两个关联?

PS:这是多表继承的情况。

【问题讨论】:

  • 这可能是因为工厂女孩 linter 正在使用活动记录表定义进行 lint 并且没有考虑应用程序级别的连接?

标签: inheritance ruby-on-rails-4 associations factory-bot rspec-rails


【解决方案1】:

通过使用子类作为“类”名称使其工作:

FactoryGirl.define do
  factory :child, class: Child, parent: :my_base do
    association :owner, factory: :user, strategy: :build
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多