Dynamic Nested Forms in Rails 2.3+ Using RJS
Developed by Jon
Rails 2.3 delivered a new feature that allows you to easily write forms in rails that can process nested attributes for related objects using the accepts_nested_attributes_for method in your models. Now there is a plugin to make adding and removing nested forms a walk in the park!
I am not going to go into detail about this feature as Ryan Daigle has an excellent write up on his blog.
However I have been looking at ways to easily add and remove nested form blocks using Javascript/RJS and came across a good method of achieving this by Marsvin on the RailsForum website.
We have used this method a few times now, so thought we would roll it up into a plugin. Simply install the plugin to give you two new view helpers that allow you to create links to add and remove these nested form item partials using RJS.
Visit the plugin’s page on GitHub to install or view the documentation.
2 Comments
Joe McGlynn
November 18, 2009
I’m not having any luck with this, I get a “compile error”.
I’ve added this line to my form:
# form is the enclosing form_builder (I’m using semantic_form_for, but it’s just an extension of form_for)
# :agenda_items is the name of the has_many attributes on the parent model (a meeting has_many agenda_items)
# ‘agenda_item’ is the id of the dom element (a div) within which I want to add the new records
The error I get is:
compile error
C:/workspace2/MeetingAdjourned/app/views/meetings/new.html.erb:18: syntax error, unexpected kEND, expecting ‘)’
@output_buffer.concat ” “; end ; @output_buffer.concat “\n”
^
C:/workspace2/MeetingAdjourned/app/views/meetings/new.html.erb:20: syntax error, unexpected kENSURE, expecting ‘)’
C:/workspace2/MeetingAdjourned/app/views/meetings/new.html.erb:22: syntax error, unexpected kEND, expecting ‘)’
Extracted source (around line #18):
15:
16:
17: “Create Meeting” %>
18:
19:
which causes this error:
compile error
C:/workspace2/MeetingAdjourned/app/views/meetings/new.html.erb:18: syntax error, unexpected kEND, expecting ‘)’
@output_buffer.concat ” “; end ; @output_buffer.concat “\n”
^
C:/workspace2/MeetingAdjourned/app/views/meetings/new.html.erb:20: syntax error, unexpected kENSURE, expecting ‘)’
C:/workspace2/MeetingAdjourned/app/views/meetings/new.html.erb:22: syntax error, unexpected kEND, expecting ‘)’
Extracted source (around line #18):
15:
16:
17: “Create Meeting” %>
18:
19:
Jon
November 19, 2009
@Joe I can’t see what line you have added in the comment. I have not heard of any incompatibilities with Formtstic but have not personally tried it. The error is suggesting you have a syntax error in terms of a missing closing bracket but thet is all I can work out from this.
Leave a comment