Reputation: 2244
I have this bit of code sitting within my destroy.js.erb to perform an ajax request to delete some object...
The <% @client.destroy %> bit is run no matter what, and will delete the client no matter what is clicked.
callback: function(e) {
if (e === true) {
return $('#edit_client_<%= @client.id %>').parent().remove();
<% @client.destroy %>
console.log(e);
}else if (e === false){
console.log(e);
}
}
How can I solve this in an elegant way?
Upvotes: 1
Views: 76
Reputation: 16316
The issue is that your file ends in js.erb
. This is part of the asset pipeline, and it means that the ERB
(Rails) bit runs before any of the JS (in fact, the JS isn't even run on the server, so you can't really reverse the order of the naming to get it to run on the server).
The simplest solution would be to add a data attribute containing the client's ID or something similar to the button that's clicked, and using that ID rather than the Ruby to generate the ID.
Re: first comment
Same thing applies. That ERB code will be run regardless of the Javascript if
, because the ERB processor doesn't understand/care about your JS if
. Best solution would be to send an AJAX request to your server, where you do the destroy
in your controller. That also has the benefit of cleanly separating your frontend and backend.
Upvotes: 2