4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails 子要素モデル保存, 削除

Last updated at Posted at 2019-05-05

#accepts_nested_attributes_for
accepts_nested_attributes_for を使ってアソーシエーション先のモデルも含めて一発で保存する!
ついでに、simple_nested_form_for & simple_fields_for について!!

##ルーティング

routes.rb
resources :fugas, only: %i[new create]

##モデル

models/fuga.rb
has_many :hoges, dependent: :destroy
accepts_nested_attributes_for :hoges, allow_destroy: :destroy, reject_if: :all_blank
models/hoge.rb
belongs_to :fuga

##コントローラー

controllers/fugas_controller.rb
def new
  @fuga = Fuga.new
  @fuga.hoges.build
end

def create
  @fuga = Fuga.create(fuga_params)
end

private
def fuga_params
  params.require(:fuga).permit(:name, hoges_attributes: [:description])
end

ストロングパラメーターで子要素のデータ受け取りも忘れないように!

views/fugas/_form.html.haml
= simple_nested_form_for @fuga do |f|
  = f.input :name
  #hoge_form
    = f.simple_fields_for :hoges do |h|
      = h.input :name
      = h.link_to_remove "削除"
  = f.link_to_add "追加", :hoges, data: {target: '#hoge_form'}

#form を作るには2パターンある
###コントローラーで予め作る

controllers/fugas_controller.rb
def new
  @fuga.hoges.build
end

newアクションのタイミングでbuildするやり方

###view で1つずつ追加していく

views/fugas/_form.html.haml
= simple_nested_form_for @fuga do |f|
  = f.input :name
  #fuga_form
    = f.simple_fields_for :hoges do |h|
      = h.input :name
      = h.link_to_remove "削除"
  = f.link_to_add "追加", :hoges, data: {target: '#fuga_form'}

link_to_addのように1つずつフォームを追加していくやり方


#まとめ
今回、私自身の作業でform の追加時に苦労したため、備忘録的な感じで記事にしました。
言葉で説明しても、ごちゃごちゃになりそうだったので、あまり書きませんでした。(書く知識がないだけです)

間違えてる箇所があればご指摘いただきたいです!

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?