Created
January 8, 2013 17:53
-
-
Save clauda/4486095 to your computer and use it in GitHub Desktop.
Rails Ajax Nested Form Sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="fields"> | |
<%= f.text_field :number, placeholder: t('activerecord.attributes.phone.number') %> | |
<%= link_to_remove_fields t('remove'), f %><br /><br /> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ApplicationHelper | |
def link_to_remove_fields(name, f) | |
f.hidden_field(:_destroy) + link_to_function(name, "nestedForms.remove_fields(this)", class: 'remove') | |
end | |
def link_to_add_fields(name, form, association, partial = nil) | |
partial = partial || association.to_s.singularize | |
new_object = form.object.class.reflect_on_association(association).klass.new | |
fields = form.fields_for(association, new_object, child_index: "new_#{association}") do |builder| | |
render("#{partial}_fields", f: builder) | |
end | |
link_to_function(name, "nestedForms.add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", class: 'add_link') | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- ... --> | |
<%= f.fields_for :phones do |phone| %> | |
<%= phone.text_field :number, placeholder: t('activerecord.attributes.phone.number') %> | |
<% end %> | |
<p><%= link_to_add_fields t('add'), f, :phones, 'profile/phone' %></p><br /> | |
<!-- ... --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var nestedForms = { | |
remove_fields: function(link) { | |
$(link).prev("input[type=hidden]").val("1"); | |
$(link).parent("div.fields").hide(); | |
}, | |
add_fields: function(link, association, content) { | |
var new_id = new Date().getTime(); | |
var regexp = new RegExp("new_" + association, "g") | |
$(link).parent().before(content.replace(regexp, new_id)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment