Adding dynamic fields to nested form through AJAX

时光怂恿深爱的人放手 提交于 2019-12-03 02:54:25

I don't have a pro account on Railscasts either, but sometimes it is a good idea to have a look at Ryan's Github account. Oftentimes he develops gems to stuff he covered in his episodes. There you will find this awesome nested_form gem, which does exactly what you want.

Of course you can reinvent the wheel, but I think it is much easier and faster to use Ryan's gem. The documentation explains perfectly how to use it. Have fun!

Did you know about remote links and forms? You can use a remote link here to accomplish what you want.

In your view:

link_to 'Add question', add_question_path(@survey), remote: true

In your controller

def add_question
  @survey = Survey.find(params[:id])

  respond_to do |format|
    format.js #add_question.js.erb
  end
end

The last step is to create a file app/views/surveys/add_question.js.erb

$('#my_survey').append('<%=j render partial: 'my_question_partial' %>')

Don't forget to create a route for your ask_question_path

For more info about remote links and forms see: http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs

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