has_one association factory_bot accepts_nested_attributes_for request_spec [for myself]

class Project < ApplicationRecord
  has_one :location, class: 'Project::Location'
  accepts_nested_attributes_for :location, allow_destroy: true
end

class Project::Location < ApplicationRecord
  belongs_to project
end

factory

FactoryBot.define do
  factory :project_location, class: 'Project::Location' do
    association :prefecture
    association :project
    address { '4-2-8 Shibakoen, Minato-ku' }
    station { 'JR Hamamatsucho Station' }
  end
end

request spec

    let!(:prefecture) { create(:prefecture) }
    let!(:category) { create(:project_category) }
    let(:project_params) do
      attributes_for(:project, location_attributes: attributes_for(:project_location,
                                                                   prefecture_id: prefecture.id)
    end

 post projects_path, params: { project: project_params }

I'll specify prefecture_id

Recommended Posts

has_one association factory_bot accepts_nested_attributes_for request_spec [for myself]
Nested class (for myself)