Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Last active December 23, 2015 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmajstor/6588081 to your computer and use it in GitHub Desktop.
Save zmajstor/6588081 to your computer and use it in GitHub Desktop.
Rails nested form (Add/Remove nested resource without Controller for nested resource) inspired by http://davidlesches.com/blog/rails-nested-forms-using-jquery-and-simpleform and http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html * to destroy the associated model: add the _destroy key to the attributes hash, with a…
= simple_form_for @portfolio do |f|
= f.input :title, label: 'Portfolio Title'
= f.simple_fields_for :assets do |assets_form|
.duplicatable_nested_form
= assets_form.association :stock
= assets_form.input :amount, :input_html => { min: 0 }
= link_to 'Remove', '', :class => 'destroy_duplicate_nested_form'
= assets_form.input :id, as: :hidden
= link_to 'Add Another Asset', '', :class => 'duplicate_nested_form'
= f.submit
$(document).on "click", ".remove_nested_form", (e) ->
e.preventDefault()
nestedForm = $(this).closest("." + $(this).data("fields"))
nestedForm.find("[name$=\"[_destroy]\"]:hidden").val "1"
nestedForm.slideUp "slow"
$(document).ready ->
# from each "id" of associated model add "_destroy" field:
$(".duplicatable_nested_form").find("[name$=\"[id]\"]:hidden").each ->
new_destroy = $(this).clone()
oldId = new_destroy.attr("id")
newId = oldId.replace(new RegExp(/id/), "_destroy")
new_destroy.attr "id", newId
oldName = new_destroy.attr("name")
newName = oldName.replace(new RegExp(/id/), "_destroy")
new_destroy.attr "name", newName
new_destroy.val "0"
new_destroy.insertAfter $(this)
$(".duplicate_nested_form").click (e) ->
e.preventDefault()
lastNestedForm = $(".duplicatable_nested_form").last()
newNestedForm = lastNestedForm.clone().hide()
formsOnPage = $(".duplicatable_nested_form").length
newNestedForm.find("label").each ->
oldLabel = $(this).attr("for")
newLabel = oldLabel.replace(new RegExp(/_[0-9]+_/), "_" + formsOnPage + "_")
$(this).attr "for", newLabel
newNestedForm.find("select, input, textarea").each ->
oldId = $(this).attr("id")
newId = oldId.replace(new RegExp(/_[0-9]+_/), "_" + formsOnPage + "_")
$(this).attr "id", newId
oldName = $(this).attr("name")
newName = oldName.replace(new RegExp(/\[[0-9]+\]/), "[" + formsOnPage + "]")
$(this).attr "name", newName
$(this).val ""
newNestedForm.find("[name$=\"[_destroy]\"]:hidden").val "0"
newNestedForm.insertAfter lastNestedForm
newNestedForm.slideDown "slow"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment