I applied a nested attribute form using the Railscast nested attributes as a guide. As a result, the user can click the icon to dynamically add “child” lines to my view.
Unfortunately, I can only do this job for the last icon in my view (shown here here ). This icon is generated in my view, and the rest are generated in partial, which is used to render each line.
Can this be done? If so, what is the best approach?
Here is my last attempt.
Sheet has_many Slots. In the sheet editing view, I use the sheet form builder to render the partial fragment and also pass it to the link_to_add_fields , which displays a link that will generate a new line when clicked (this part works fine), you will notice that I'm also trying to pass sheet partial so that I can call link_to_add_fields from there, but here it breaks down:
View - edit.html.haml :
= sheet.fields_for :slots do |builder| = render 'slots/edit_fields', f: builder, sheet:sheet = link_to_add_fields image_tag("plus.jpg", size:"18x18", alt:"Plus"), sheet, :slots, 'slots/edit'
Partial - _edit_fields.html.haml :
- random_id = SecureRandom.uuid .row.signup{:id => "edit-slot-#{random_id}"} .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 ... other fields ...
Helper Method:
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
I get an undefined local variable or method 'sheet' in the helper call from partial. Basically, I need a sheet (parent) form builder that will be available on every link for the assistant to work. Or I need to abandon this approach and use AJAX (also tried this).
UPDATE
After debugging the bit, it is clear that sheet is passed to partial. The root problem is that I seem to set up infinite recursion:
- Partial calls
link_to_add_fields , so the + icon can serve as an add child link. link_to_add_fields displays partial so that fields can be generated when you click the + icon.
Another problem that I am facing is that when the original children are displayed, they get sequential indexes in the attribute collection (0, 1, 2, ...). That way, even if I figure out a way to visualize new child lines among the originals, I'm not sure how I can maintain the order of the children when the form is submitted without much jQuery charging or something like that.