vendredi 8 mai 2015

Generating dynamic child rows in partial

I have implemented a nice nested attribute form using the excellent nested attributes Railscast as a guide. As a result, the user can click an icon to dynamically add "child" rows to my form. When I try to make the original rows work the same way, I find that I cannot pass the parent object to the partial as a local. Is there a better way to do this?

Pertinent code snippets:

My view (builds the children and creates link to add more rows):

= sheet.fields_for :slots do |builder|
  = render 'slots/edit_fields', sheet:sheet, f: builder, slots: :slots
= link_to_add_fields image_tag("plus.jpg", size:"18x18", alt:"Plus"), sheet, :slots, "slots/edit"

... the above works except for sheet: sheet - this is Nil in my partial.

My partial:

.row.signup
  .col-md-1
    %span.plus-icon
      = link_to_add_fields image_tag("plus.jpg", size:"18x18", alt:"Plus"), sheet, slots, "slots/edit"
    %span.minus-icon
      = image_tag "minus.jpg", size:"18x18", alt:"Minus"
  .col-md-2= f.text_field :label
  .col-md-2= f.text_field :name
  .col-md-2= f.text_field :email
  .col-md-2= f.text_field :phone
  .col-md-2= f.text_field :comments

My helper:

module ApplicationHelper
  def link_to_add_fields(name, f, association, partial)
    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(partial.to_s.singularize + "_fields", f: builder, name: name)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end
end

... since I cannot pass sheet to my partial, I can't get f defined here and am not able to generate new_object.

The error I get is undefined local variable or method 'sheet' for #<#<Class:0x007f2f19080e18>:0x007f2f04442f70> on the link_to_add_fields call in the partial and when I debug, the value is Nil as I mentioned.

Thanks in advance for your help and suggestions. I am about to give up and implement this with Ajax but am hoping I am close to a more elegant solution.

Aucun commentaire:

Enregistrer un commentaire