###動作環境
ruby 2.4.4p296
Rails 5.2.0
gem 'nested_form_fields'
gem 'jquery-rails' (4.3.3)
現在行っていること・問題
・動的フォームの作成(自身で投げた質問です)を無事解決し、nested_form_fieldsで動的フォームの追加・削除機能を実装中です。
・親モデルのedit・updateアクションに実装し、子レコードは一括で作成・編集・削除できるようにしたいです(画像参照)。
・追加ボタンは正常に機能するのですが、削除ボタンを押してもフォームが削除されず、なぜかページの読み込みが行われてしまいます。追加はできるので、application.jsの読み込みは正常だと思うのですが...
何が原因なのでしょうか?お詳しい方々、どうか回答のほどよろしくおねがいします。
参考にしたサイト
Ruby on Railsで動的に追加・削除可能な入力フォームの実装手順
プログラム
application.js
js
1//= require jquery <---追加 2//= require rails-ujs 3//= require activestorage 4//= require turbolinks 5//= require_tree . 6//= require nested_form_field <---追加
edit.html.erb (view)
html
1<%= form_for @project,url: project_path do |f| %> 2 3-----親モデルの編集部分(省略)----- 4 5 <%= f.nested_fields_for :checklists, wrapper_tag: :div do |che| %> 6 <%= che.text_area :content, :class => "text-area", :size => "50×15"%> 7 <%= che.remove_nested_fields_link '削除', class: 'btn btn-danger', role: 'button' %> 8 <% end %> 9 10 <%= f.add_nested_fields_link :checklists, '--------追加--------', class: 'btn btn-primary', role: 'button' %> 11 <%= f.submit "保存", :class=> "link-button"%> 12<% end %>
projects_controller.rb 一部(controller)
ruby
1def edit 2 @project = Project.find(params[:id]) 3 @project.checklists.build 4 end 5 6 def update 7 @project = Project.find(params[:id]) 8 if @project.update(project_params) 9 redirect_to action: 'index' 10 else 11 render 'edit' 12 end 13 end 14 15def project_params 16 params.require(:project).permit(:name, :content, checklists_attributes: [:id, :content, :_destroy]) 17 end
project.rb (親Model)
ruby
1class Project < ApplicationRecord 2 has_many :checklists, dependent: :destroy 3 accepts_nested_attributes_for :checklists, allow_destroy: true 4end
checklist.rb (子Model)
ruby
1class Checklist < ApplicationRecord 2 belongs_to :project 3end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。