gem --- cocoon

1.Inside your Gemfile add the following:

gem “cocoon”

2.Add the following to application.js so it compiles to the asset pipeline:

//= require cocoon

3.model文件中添加(一级)
accepts_nested_attributes_for :tasks, allow_destroy: true

4.在一级model的controller里面的params里面加上
tasks_attributes: [:id, :description, :done, :_destroy(有这个才能删除)]
以数组形式存入数据
在def new下面加上
@dish.materials.build

5.form 文件中添加

1
2
3
4
5
6
7
8
9
10
11
<div class="form-action">
<%= link_to_add_association '新增用料', f, :materials, class: 'btn btn-success',
'data-association-insertion-node' => '.materials',
'data-association-insertion-method' => 'append' %>
</div>

<div class="materials">
<%= f.fields_for :materials do |m| %>
<%= render 'material_fields', f: m %>
<% end %>
</div>
1
2
3
4
5
6
7
8
<div class="detail-tr form-action">
<%= f.hidden_field :id %>
<%= f.select(:good_id, Good.where(:goods_first_category => '1').map{|g| [g.name, g.id]}, {:include_blank=>"请选择菜品用料"}, :style => 'width: 200px;') %>
<%= f.text_field :amount, placeholder: '请输入菜品用量' %>g
<%= link_to_remove_association('删除', f,
{ wrapper_class: 'detail-tr' })%> #只有model中添加了那个destroy 才能用

</div>

ps: 1.要注意各个地方的名称对应
2.要给多个地方联动取值的时候 用tag+mark 或者 clas+mark ,不要用id+mark(这样只能取到第一个值)