1. 安装gem包
gem 'nested_form'
增加jquery效果,在application.js中添加
//= require jquery_nested_form
执行bundle install
2. 新建两个Model
Event
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :title
t.text :expression
t.timestamps null: false
end
end
end
Task
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.integer :event_id
t.text :name
t.text :dothing
t.timestamps null: false
end
end
end
3. 确定Model之间的关系
class Event < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks, :allow_destroy => true, :reject_if => :all_blank
end
class Task < ActiveRecord::Base
belongs_to :event
end
4. 修改controller
def event_params
params.require(:event).permit(:title, :expression, :tasks_attributes=>[:id, :name, :dothing, :_destroy])
end
5. 修改view
<%= nested_form_for(@event) do |f| %>
<% if @event.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@event.errors.count, "error") %> prohibited this event from being saved:</h2>
<ul>
<% @event.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :expression %><br>
<%= f.text_area :expression %>
</div>
###############################新增#######################
<%= f.fields_for :tasks do |t| %>
<%= t.text_field :name, :class => 'my_class', :mthd=>'clickd' %>
<%= t.text_field :dothing %>
<%= t.link_to_remove "移除此待办事项" %>
<% end %>
<%= f.link_to_add "新增待办事项", :tasks %>
###############################新增#######################
<div class="actions">
<%= f.submit %>
</div>
<% end %>
6. 解释
因为我们在model里面有加上:reject_if => :all_blank,所以如果把需要填入资料的地方都留白,就不会储存,同等于把这个数据删除;这个方法可以间接用来删除不想要的数据。
如果刚刚的设置有错误,可能就会发生一次增加多个数据、或是明明删了数据却有储存等窘境。
网友评论