Reputation: 324
I can't figure out how to destroy a record on click using coffee script/jquery. Normally I would use button_to rails helper but under the circumstances I can't.
<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()
Upvotes: 1
Views: 184
Reputation: 54902
There is a little hack in the HTTP verbs since not all browsers uses (respects?) the standard HTTP verbs:
$('#delete_record_button').click (e) =>
e.preventDefault()
$.post(
'#{path_to_update_action}',
{ user_id: #{current_user.id}, id: #{delete_this.id}, '_destroy': true },
handler
)
Where handler can either be an anonymous function or a defined callback.
I used the extra POST params _destroy
set to true
in order to send a destroy call on the record.
If you don't want Rails to recompile your assets each time the view/coffeescript is used (on Linux systems: insignificant, on Windows: VERY significant), you can use this workaround:
# 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)
References :
Upvotes: 2