ruby on rails - Empty associations for fields_for if the content is added dynamically via jquery -
i built form_for 4 associated models. created nested fields_for can added dynamically code below. form works if call 'edit' method if use method below add new data fields_for remains empty , not shown.
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) |builder| render(association.to_s.singularize + "_fields", f: builder) end link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")}) end
this works fine if wants add 1 form of model. if added content have fields_for nested fields_for text_fields not created. in opinion because not build associations. how can fix method this?
i have similar method (based on itay grudev's blog post), in set child_index
nil
, use jquery replace timestamp (so many records can added avoiding them having same id
).
so, in application_helper.rb
file i've got:
def link_to_add_fields(name = nil, f = nil, association = nil, options = nil, html_options = nil, &block) f, association, options, html_options = name, f, association, options if block_given? options = {} if options.nil? html_options = {} if html_options.nil? if options.include? :locals locals = options[:locals] else locals = { } end if options.include? :partial partial = options[:partial] else partial = association.to_s.singularize + '_fields' end new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, child_index: nil) |builder| render(partial, locals.merge!( fields: builder)) end html_options['data-form-prepend'] = raw cgi::escapehtml( fields ) html_options['href'] = '#' content_tag(:a, name, html_options, &block)
end
and added coffeescript file called dynamic_tables.js.coffee
in find newly added fields, replace name timestamp (so they're indexed group) , prepend form target (a hidden element added @ bottom of table , marked prepend_target
). i've got:
$('[data-form-prepend]').click (e) -> target = $($(this).attr('prepend_target')) obj = $($(this).attr('data-form-prepend')) current_time = (new date).gettime() obj.find('input, select, textarea').each -> $(this).attr 'name', -> $(this).attr('name').replace 0, current_time return obj.insertbefore target false
that should trick. hope helps.
Comments
Post a Comment