我有一个带有父Foo和子Bar的嵌套模型窗体。
我紧随其后http://railscasts.com/episodes/196-nested-model-form-revised通过为我做这个设置,效果很好。我可以通过javascript(根据railscast)轻松添加和删除Bars
背景:
我在酒吧有一个必填字段"姓名"。
问题:
如果用户将名称字段留空,然后删除该栏(通过javascript),它将不允许我保存表单。我不会收到任何通知。我相信,由于客户端验证已经将其踢到了我删除的必填字段上,表单不允许我提交到服务器。
Foo.rb
validates :title, presence: true
has_many bars
accepts_nested_attributes_for :workouts, :allow_destroy => true
Bar.rb
validates :name, presence: true
views/foos/_form.html.haml
= simple_form_for(@foo) do |f|
.form_inputs
= f.input :title
= f.simple_fields_for :bars do |p|
= render "bar_fields", f: p
%br
= link_to_add_fields "Add Bar", f, :bars
%br
= f.button :submit
views/foos/_bar_fields.html.haml
%h4 Bar
= f.input :name
= f.input :description
= f.hidden_field :_destroy
= link_to "Delete Bar", '#'
helpers/application_helper.rb
def link_to_add_fields(name, f, association, css_class = "add_fields btn btn-sm btn-info icon-plus")
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: css_class, data: {id: id, fields: fields.gsub("n", "")})
end
application.js
function remove_fields_(link) {
$(link).prev("input[type='hidden']").val("true");
$(link).closest(".fields").hide();
}
我做错了什么?有什么变通办法吗?
在代码示例中看不到"accepts_nested_attributes_for:bars",请确保使用此选项。