現象
こんな感じで作っていたら、createだけinvalidになる。
updateはOK。何故だ??
Model
app/model/product.rb
class Product < ApplicationRecord
has_one :image
accepts_nested_attributes_for :image,
allow_destroy: true
end
app/model/image.rb
class Image < ApplicationRecord
belongs_to :product
end
Controller
app/controller/products_controller.rb
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
respond_to do |format|
# ここでsaveが必ず失敗する
if @product.save
format.html { redirect_to @product, notice: '新規作成しました' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
View
<%= f.fields_for :image, @product.image || @product.build_image do |image| %>
<%= f.file_field :path %>
<% end %>
原因
結論から言うと多分これのせいじゃないかなーと。
belongs_to should default to required: true
上記の例で言うと
①ProductはImageが無いとinvalidになり、
②ImageはProduct保存後でないと親レコードのIDが決まらないので保存できない。
対策
以下の様にして、requiredを解除して①を解消すれば保存できるようになりました
app/model/image.rb
class Image < ApplicationRecord
belongs_to :product, optional: true
end