Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails AJAX: My partial needs a FormBuilder instance

So I've got a form in my Rails app which uses a custom FormBuilder to give me some custom field tags

<% form_for :staff_member, @staff_member, :builder => MyFormBuilder do |f| %>
[...]
    <%= render :partial => "staff_members/forms/personal_details", :locals => {:f => f, :skill_groups => @skill_groups, :staff_member => @staff_member} %>  
[...]
<% end %>

Now, this partial is in an area of the form which gets replaces by an AJAX callback. What I end up doing from the controller in response to the AJAX request is:

render :partial => "staff_members/forms/personal_details", :locals => {:skill_groups => @skill_groups, :staff_member => @staff_member}

However, if I do that then the form breaks, as the FormBuilder object I used in the form_for is no longer available. Is there any way for me to use my custom FormBuilder object inside a partial used for an AJAX callback?

like image 356
Gareth Avatar asked Dec 16 '08 12:12

Gareth


4 Answers

Use fields_for inside your partial. It performs a similar task but without wrapping the form tags. See the API docs.

like image 160
Edd Avatar answered Nov 14 '22 03:11

Edd


how about this?

  @template.with_output_buffer do
    @template.form_for @model_object do |f|
      f.fields_for :some_nested_attributes do |ff|
        render :partial => 'nested_attributes', :object => @model_object, :locals => {:form => ff}
      end
    end
  end

this would be especially useful is you need to use the nested fields_for in the partial

like image 32
David Lowenfels Avatar answered Nov 14 '22 04:11

David Lowenfels


You could instantiate a new instance of your form builder in the controller, though it feels sort of lousy to me:

# in the controller
render :partial => {
  :f => MyFormBuilder.new(:staff_member, @staff_member, template),
  :skill_groups => @skill_groups,
  :staff_member => @staff_member
}

Alternatively, you could move more of the update logic to be client side which wouldn't require you to worry about rendering anything at all. You could just update the values via JS. Not sure if that works for your project though.

like image 1
nakajima Avatar answered Nov 14 '22 04:11

nakajima


Maybe I'm a little late in the game here, and maybe I don't understand the question properly, but in ApplicationHelper.rb I think you can just add the line:

ActionView::Base.default_form_builder = MyFormBuilder
like image 1
Samo Avatar answered Nov 14 '22 04:11

Samo