As in Railscasts196, I have nested Attendances
in Events
, Events
in Event_groups
:
= simple_form_for(@event_group) do |f|
= f.error_notification
.form-inputs
= f.input :name
.form-actions
= f.button :submit
.h2 Events (not simple form)
= f.fields_for :events do |p|
= link_to_add_fields "Add field", p, :fields
.field
= p.label :starts_at
= p.hidden_field :_destroy
= link_to "[remove]", '#', class: "remove_fields"
%p
= p.fields_for :attendances do |f|
.field
= f.label :guest_id
= f.text_field :guest_id
= f.label :attendance_rate_id
= f.text_field :attendance_rate_id
Event_groups.js:
$(document).on 'click', 'form .remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$(document).on 'click', 'form .add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
Application_helper.rb:
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
Now I can't make the jQuery work as in Railscasts for Delete
and Add new
. Something must be wrong with the link_to_add_fields
& remove
. Please help
Actually, nowadays there's a better way, using the cocoon gem.
It's very simple and I've had great success using it ;) hope you do too!