首先说一下需求吧:
联系人信息的增删改查,每个联系人都会可能有多个电话,在不用ajax的情况下去实现这种信息在一个页面上的操作
通过嵌套属性(nested attribute),你可以通过parent来保存与其相关联的属性。默认情况下,嵌套属性是关闭的,你可以开启accepts_nested_attributes_for这个类方法,就在该model上生成并绑定一个属性 。例如,为你的model增加两个新方法:
class Bid::Contact < ActiveRecord::Base
has_many :telephones
accepts_nested_attributes_for :telephones, allow_destroy: true
end
由于我们要在联系人刚新建的时候就需要给一个电话和邮箱的输入框,所以我们要在controller页面做一些初始化:
@bid_contact = Bid::Contact.new
@bid_contact.telephones.build
在view页面我们最好单独给电话信息的录入框做一个页面:(_firm_field.html.haml)
%table.col-md-8.col-xs-8
%thead
%tr
%td= f.input :country_num, as: :string, wrapper: :table_fields_for, placeholder:'国家代码', readonly: true
%td= f.input :phone_num, wrapper: :table_fields_for, placeholder:'电话号码'
%td= f.input :ext, wrapper: :table_fields_for, placeholder:'分机号'
%td= f.input :note, wrapper: :table_fields_for, placeholder:'备注'
%td.col-md-1
= f.hidden_field :_destroy
= link_to "删除", "javascript:void(0)", class: "remove_fields "
在bid_contact页面则可以这么写:
%tr
%th 电话
%td= f.simple_fields_for :telephones do |builder|
= render '/bid/firms/phone_field', f: builder
.form-actions
= link_to_add_fields "添加电话录入框", f, :telephones , "phone_field"
#我们需要给表格的电话信息的表单存在添加按钮里,所以就自己写了一个生成按钮的方法
def link_to_add_fields(name, f, association, partial=nil, link_options={})
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
partial ||= association.to_s.singularize + "_fields"
render(partial, f: builder)
end
link_to(name, 'javascript:void(0)', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")},style:link_options[:style])
end
控制添加移除电话项的按键事件可以这么写:
$('form').on('click', '.add_fields', function(event){
$(this).before($(this).data('fields'));
event.preventDefault();
});
//设定_destroy的值为true,这表示删除这一项
$('.remove_fields').click(function (event) {
$(this).prev('input[type=hidden]').val('true');
$(this).closest('table').hide();
event.preventDefault();});
网友评论