Ruby On Rails 使用 Jquery 動態新增Form
介紹nested_fields_for
在Gemfile安裝gem 'nested_form_fields'
在app\assets\application.js新增
//= require nested_form_fields
class EventAttachment < ApplicationRecord
has_many :attachments, :class_name => "EventAttachment", :dependent => :destroy
accepts_nested_attributes_for :attachments, :allow_destroy => true, :reject_if => :all_blank
end
accepts_nested_attributes_for這個方法可以讓更新event資料時,也可以直接更新location的關聯資料。也就是說,我們可以完全不需要修改events_controller的新增和編輯Action,就可以透過本來的params[:event]參數來新增或修改location了。
這裡有兩個特別的參數,:allow_destroy是說我們可以在表單中多放一個_destroy核選塊來表示刪除,而:reject_if表示說在什麼條件下,就當做沒有要真的動作,例如:all_blank就表示如果資料都是空的,就不建立location資料(當然也就不會檢查location的驗證了)。這是因為雖然要顯示location表單,但是不表示使用者一定要輸入。有輸入就表示必須通過Location Model的資料驗證。詳情可以參考 ihower大神
<%= f.nested_fields_for :attachments do |ff| %>
<fieldset style="border-left: 5px solid #bbb; margin-bottom: 10px; padding: 10px;">
<div class="form-group">
<%= ff.label :description %>
<%= ff.text_field :description, :class => "form-control" %>
</div>
<%= ff.remove_nested_fields_link "移除表單", :class => "btn btn-danger" %>
</fieldset>
<% end %>
<p class="text-right">
<%= f.add_nested_fields_link :attachments, "新增表單", :class => "btn btn-default" %></p>
使用nested_fields_for把整個妳要用複製的表單包起來
使用remove_nested_fields_link去做移除表單的動作
注意remove_nested_fields_link需要在nested_fields_for範圍中調用,並通過父構建器在它的外部調用add_nested_fields_link。也可以使用以下方式添加額外的屬性。
ff.remove_nested_fields_link '移除表單', class: 'btn btn-danger', role: 'button', data: { confirm: 'Are you sure?' }
f.add_nested_fields_link :attachments, '新增表單', class: 'btn btn-primary', role: 'button'