LoginSignup
7
2

More than 5 years have passed since last update.

has_one かつ presence: true な関連をもつモデルを factory_bot で定義する

Posted at

こんな感じで has_one かつ presence: true な関連を作りたいとします1:

class A < ApplicationRecord
  has_one :b
  validates :b, presence: true
end

class B < ApplicationRecord
  belongs_to :a
end

この2つのモデル A Bfactory_bot を使って正しく定義するには以下のように書きます:

FactoryBot.define do
  factory 'a' do
    after(:build) do |instance|
      build('b', a: instance) unless instance.b
    end
  end

  factory 'b' do
    association :a, factory: 'a', strategy: :build
    after(:build) do |instance|
      instance.a&.b = instance
    end
  end
end

このように書くことで build('a') build('b') のどちらも永続化されていない正しい状態の AB インスタンスを生成することができます。


  1. 「わざわざテーブルを分けるくらいなら、 B の属性を A に含めればいいじゃないか」という指摘もあると思いますが、世の中にはどうしてもこうせざるを得ない状況というのも存在するのです。 

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2