Last active
November 3, 2015 21:53
-
-
Save longlostnick/3420e70972cc6cf93b3f to your computer and use it in GitHub Desktop.
FormBuilder addition for models that accept nested attributes.
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
function addNestedRow(e) { | |
e.preventDefault(); | |
// http://railscasts.com/episodes/197-nested-model-form-part-2 | |
var html = $('#my-attribute-link-template').html(); | |
var $attr_row = $(html.replace(/new_MyAttribute/g, new Date().getTime())); | |
$('#my-attributes').append($attr_row); | |
}; |
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
class FormBuilder | |
def accept_nested_attributes_for(attribute) | |
attribute = attribute.to_s | |
singular = attribute.singularize | |
humanized = singular.underscore.humanize.titleize | |
css_class = attribute.underscore.dasherize | |
css_class_singular = css_class.singularize | |
"".tap do |html| | |
html << @template.content_tag(:div, id: css_class) do | |
simple_fields_for attribute do |c| | |
yield(c) | |
end | |
end | |
html << @template.link_to("+ Add #{humanized}", '#', id: "add-#{css_class_singular}") | |
html << @template.content_tag(:script, id: "#{css_class_singular}-template", type: "text/x-handlebars-template") do | |
simple_fields_for attribute, singular.constantize.new, child_index: "new_#{singular}" do |c| | |
yield(c) | |
end | |
end | |
end.html_safe | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment