LoginSignup
0
0

More than 5 years have passed since last update.

[Ruby on Rails]ネストされたモデルをBuildし、空文字がきたら無視する方法

Posted at

概要

関連モデルを一緒に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

0
0
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
0
0