RailsCasts Pro episodes are now free!

Learn more or hide this

Alexander Schomburg's Profile

GitHub User: alexschomb

Site: http://alex.schomb.org

Comments by Alexander Schomburg

Avatar

Too bad I wasted so much time implementing your railscast solution in rails 3.2. I just found out that the 'nested_forms' gem is pretty straight forward.
FIW here are some changes I made to your helper methods to let them allow blocks, as the original link_to_function method does:

/app/helpers/form_helper.rb
def link_to_remove_fields(*args, &block)
  if block_given?
    element = args.first || {}
    html_options = args.second
    link_to_remove_fields(capture(&block), element, html_options)
  else
    name = args[0]
    element = args[1]
    html_options = args[2] || {}
    element.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)", html_options)
  end
end
def link_to_add_fields(*args, &block)
  if block_given?
    element = args.first || {}
    association = args.second
    html_options = args.third
    link_to_add_fields(capture(&block), element, association, html_options)
  else
    name = args[0]
    element = args[1]
    association = args[2]
    html_options = args[3] || {}
    new_object = element.object.class.reflect_on_association(association).klass.new
    fields = element.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", html_options)
  end
end
Avatar

Where's the difference to the nested_forms gem? I can use the latter with one-to-many associations. Unsure about many-to-many, though I can't see why this wouldn't work, too.