Nested Model Forms - Railscast #196 revised - Adding fields via jQuery not working

放肆的年华 提交于 2019-12-04 13:42:30

I found via accident Railscast #403 on Dynamic Forms in which nested forms were briefly part of the tutorial, too. Ryan used in this episode an edited code for the javascript part to make the code compatible with Turbolinks. I tried the version below in my postfiles.js.coffee and it worked! The add fields link is finally generating new fields.

$(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()

You should watch out for singular and plural forms. The file name of your model should be postfile.rb instead of postfiles.rb

Same goes for the _postfiles_fields.html.erb which should be _postfile_fields.html.erb

So, basically the function can't find the template, because it's in plural and not singular form, but it gets called by its singular form. Change this and you should be fine. Rest of the code looks good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!