我按照 Ryan Bates 的教程(第 196 集 - 嵌套模型表单(修订版))为模型创建了一个表单(Employee
)和嵌套has_many :through
模型(Capability
)。在大多数情况下它都有效;但是,当我单击链接以将新模型对象添加到表单时,会创建并插入两个。我不知道为什么-我已经为此苦苦挣扎了几个晚上,但无法解决。谁能指出我哪里出错了?
(Capability
这里代表一个has_many through
关联:)Employee has_many :roles, through: :capabilities
。
形成部分
<%= form_for(@employee) do |f| %>
# Employee fields here ...
<%= f.fields_for :capabilities do |builder| %>
<%= render 'capability_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add capability", f, :capabilities %>
<%= f.submit "Submit", :class => 'submit' %>
<% end %>
能力字段部分
<fieldset>
<%= f.select :role_id, Role.all.collect{ |r| [r.name, r.id]} %>
<%= f.check_box :primary_role_flag %>
<%= f.text_field( :valid_from, :class => 'date') %>
<%= f.text_field( :expires_on, :class => 'date') %>
<%= f.hidden_field :_destroy %>
<%= link_to "Remove", '#', class: "remove_fields" %>
</fieldset>
link_to_add_fields 应用程序助手
def link_to_add_fields(name, f, association)
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|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub('\n','
')})
end
jQuery 咖啡脚本
jQuery ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()