使用jquery / coffee脚本删除没有button_to帮助程序的记录

时间:2014-07-18 17:55:06

标签: jquery ruby-on-rails coffeescript xmlhttprequest

我无法弄清楚如何使用coffee script / jquery销毁点击记录。通常情况下,我会使用button_to rails helper,但在这种情况下我不能。

<form id="instance_delete" action="<%= url_for my_url_delete_path(current_user.id, delete_this.id) %>" 
data-remote="true" method="delete"><%= link_to "Delete", "#", id: "delete_record_button"%> </form>


($ '#delete_record_button').click (e) =>
   e.preventDefault()
   ($ e.target.form).submit()

1 个答案:

答案 0 :(得分:2)

HTTP谓词有点破解,因为并非所有浏览器都使用(尊重?)标准HTTP谓词:

$('#delete_record_button').click (e) =>
   e.preventDefault()
   $.post(
     '#{path_to_update_action}',
     { user_id: #{current_user.id}, id: #{delete_this.id}, '_destroy': true },
     handler
     )

其中handler可以是匿名函数,也可以是定义的回调函数。

我使用额外的POST参数_destroy设置为true,以便在记录上发送销毁调用。


如果您不希望Rails在每次使用view / coffeescript时重新编译您的资产(在Linux系统上:无关紧要,在Windows上:非常重要),您可以使用此解决方法:

# haml file or seperated files but both included:
:javascript
  var path_to_update_action = "#{path_to_update_action}";
  var current_user_id = #{current_user.id};
  var id_to_delete = #{delete_this.id};

:coffeescript
  $('#delete_record_button').click (e) =>
    e.preventDefault()
    $.post(
      path_to_update_action,
      { user_id: current_user_id, id: id_to_delete, '_destroy': true },
      handler)

参考文献:

相关问题