webエンジニアの日常

RubyやPython, JSなど、IT関連の記事を書いています

ActiveRecord::RecordNotSaved: Failed to save the new associated ~ と言われたとき

Railsアプリで、1対1の関係にあるモデルを実装したときに少しはまったのでメモ。

例えば以下のようなモデルがあるとします。

class CarManager
  has_one :car
  accepts_nested_attributes_for :car, reject_if: :all_blank, allow_destroy: true
end

class Car
  belongs_to :car_manager
end

このとき、例えばnewアクション内では、

def new
  @car_manager = ::CarManager.new
  @car_manager.car = ::Car.new
end

とすることで、CarManagerに紐づいたCarクラスのインスタンスがつくられます。

ですが、editアクションなどで、同じように

def edit
  @car_manager = ::CarManager.find(params[:id])
  @car_manager.car = ::Car.new
end

とすると、「ActiveRecord::RecordNotSaved: Failed to save the new associated car」 と言われてしまいます。

詳しくソースを見てないのでなぜエラーになるのか分かりませんが、

def edit
  @car_manager = ::CarManager.find(params[:id])
  @car_manager.build_car
end

とすればいけました。