Search code examples
ruby-on-railspartialsfields-for

Dynamic content with fields_for


I have a nested form that uses a has_many relationship. In my form view, I use a partial for the field inputs and pass along the FormBuilder object.

form.html.haml:

- form_for @record do |f|
  .field
    = container do
      - f.fields_for :strings do |s|
        = render :partial => 'string_fields', :locals => {:s => s}

_string_fields.html.haml:

= s.hidden_field :id
= s.hidden_field :language_id

.field
  %h3
    = t(:name)
  = s.text_field :name, :size => 50

.field
  %h3
    = t(:description)
  = s.text_area :description, :rows => 6

This works as it should; however, I'd like to add functionality in AJAX to dynamically add another set of fields using RJS, and when I try to render the partial through RJS, obviously s isn't defined (I don't know what I'd pass through the :locals hash).

Is there some way to properly add field dynamically to a field set defined by fields_for, or do I have to reimplement my partial without using the helpers?


Solution

  • It's possible to add fields dynamically with your current implementation, look at:

    http://railscasts.com/episodes/197-nested-model-form-part-2

    for inspiration