【问题标题】:Create parent and child factory having has_many relationship创建具有 has_many 关系的父子工厂
【发布时间】:2019-06-14 16:46:09
【问题描述】:

我有一个医院和患者模型。医院与患者有很多关系。我在医院模型validates :patients, :presence => true 中进行了验证检查。添加此验证检查后,控制器的 rspecs 失败,这只是创建医院对象。我试图创建一个可以创建医院和患者的工厂,但到目前为止没有运气。这是我到目前为止所尝试的。

FactoryBot.define do
  factory :hospital do
    hospital_id { Faker::Crypto.unique.md5 }
    name { 'something' }
    departments { 'some description' }

    after(:create) do |hospital|
      create(:patient, patient_id: hospital.id)
    end
  end
end

知道我做错了什么吗?

【问题讨论】:

  • IINM 基于上述,您正在创建 patient 之后 hospital 因此验证失败,因为验证需要 patient(创建hospital时)
  • 我不知道强制医院接受此类验证是否有很大价值。如您所见,它使创建医院记录变得更加困难。这样的验证不会阻止您以后删除所有患者记录,从而使您的医院无效且无法保存。

标签: ruby-on-rails ruby


【解决方案1】:

我以前做过这样的事情;不记得了,但你可以试试下面的吗?

FactoryBot.define do
  factory :hospital do
    # ...

    after(:build) do |hospital|
      hospital.patients << build(:patient, hospital: hospital)
      # I think this needs to be assigned directly to the `hospital` object itself so that it shares the same memory space
      # when `save` is called on `hospital`, the `.patients` also get `save`d
    end
  end
end

如果上面的方法不行,你可以试试这个吗?

FactoryBot.define do
  factory :hospital do
    # ...

    after(:build) do |hospital|
      hospital.patients.build(
        attributes_for(:patient, hospital: hospital)
      )
    end
  end
end

【讨论】:

    【解决方案2】:
    factory :hospital do
      after :create do |hospital|
        create :hospital, patient: patient
      end
    end
    

    这是一个不错的备忘单:https://devhints.io/factory_bot

    【讨论】:

      【解决方案3】:

      就像我在评论中所说的那样,这种验证可能不会很有帮助。但我认为他们这样做的唯一方法是在一个save 电话中拯救医院和患者。因此,您可能需要在保存医院之前将未保存的患者添加到医院关联。 Rails 会自动保存未保存的关联。

      试试这个:

      FactoryBot.define do
        factory :hospital do
          hospital_id { Faker::Crypto.unique.md5 }
          name { 'something' }
          departments { 'some description' }
      
          before(:create) do |hospital|
            build(:patient, hospital: hospital)
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        相关资源
        最近更新 更多