Skip to content

Instantly share code, notes, and snippets.

@ogryzek
Last active August 29, 2015 13:56
Show Gist options
  • Save ogryzek/9257104 to your computer and use it in GitHub Desktop.
Save ogryzek/9257104 to your computer and use it in GitHub Desktop.
accepts_nested_attributes
%fieldset.answer
= f.label :title
= f.text_field :title
= f.label :body
= f.text_field :body
= f.check_box :_destroy
= f.label :_destroy
%br
= form_for(@question) do |f|
- if @question.errors.any?
#error_explanation
%h2
= pluralize(@question.errors.count, "error")
prohibited this question from being saved:
%ul
- @question.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :title
%br
= f.text_field :title
.field
= f.label :body
%br
= f.text_area :body
%h3 Options
= f.fields_for :options do |opt|
= render "option_fields", f: opt
= link_to_add_fields "Add Option", f, :options
%br
= f.submit
module ApplicationHelper
def link_to_add_fields(anchor_text, form_object, association)
new_nested_object = form_object.object.send(association).new
id = new_nested_object.object_id
field_html = form_object.fields_for(association, new_nested_object, child_index: id) do |ff|
render(association.to_s.singularize + "_fields", f: ff)
end
link_to(anchor_text, "javascript:void(0);", class: "add_fields",
data: {id: id, field_html: field_html.gsub("\n", "")})
end
end
$(document).on "click", "form .add_fields", ->
time = new Date().getTime()
regex = new RegExp($(this).data("id"), "g")
item_fields_html = $(this).data("field-html").replace(regex, time)
$(this).before(item_fields_html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment