概要
関連モデルを一緒にCreateしたい状況でBuildした子モデルの
パラメータが空文字で渡ってきた場合のメモです。
- まず普通に一緒にCreateする状況を作成
Model(親)
class Hoge01 < ActiveRecord::Base
has_many :hoge02s
accepts_nested_attributes_for :plan_images
end
Model(子)
class Hoge02 < ActiveRecord::Base
belongs_to :hoge
end
View
= form_for @hoge01 do |f|
= f.text_fild :text_hoge01
= f.fields_for :hoge02s do |q|
= q.text_fild :text_hoge02
Controller
def new
@plan = Plan.new
# 2回buildしてみる
2.times do
@plan.hoge02s.build
end
end
そうすると、下記の感じでパラメータがわたってくる
"hoge01"=>
{"text_hoge01"=>"入力しました",
"text_hoge02_attributes"=>{"0"=>{"text_hoge02"=>""}, "1"=>{"text_hoge02"=>""}},
"controller"=>"client/plans",
"action"=>"create",
}
ここでtext_hoge02_attributes
でネストされた子モデルが
作成しようとしてきます。
解決法
それを回避するために親モデルの設定を変更する
has_many :hoge02s
accepts_nested_attributes_for :hoge02s, reject_if: proc { |obj| obj[: text_hoge02].blank? }
reject_if
に渡す条件は他にも色々できます!
参考
ActiveRecord::NestedAttributes::ClassMethods
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html