0

I have a nested model form with parent Foo and child Bar.

I followed http://railscasts.com/episodes/196-nested-model-form-revised through getting this setup for me. It was worked great. I can add and delete Bars easily, through javascript (per the railscast)

Background:

I have a required field of "name" in Bar.

Problem:

If the user leaves the name field blank and then deletes that Bar (through javascript), it does not let me save the form. I do not get any sort of notification. I believe because of the client side validation has kicked it on the required field that I deleted, the form won't let me submit to the server.

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();
}

What am I doing wrong? Any workaround?

Ervin E
  • 442
  • 5
  • 18

1 Answers1

0

Don't see 'accepts_nested_attributes_for :bars' in your code example, be sure you use this.

Tim
  • 46
  • 4
  • thanks. I do have that in my code as well, I just forgot to copy it here. I can definitely create the records. my only problem is when I "delete" the nested records via javascript, when i hit save, it is still vaidating on the deleted records. – Ervin E Mar 07 '14 at 05:13