This time we will implement the asynchronous deletion function using rails and js. Please note that jQuery is not used for learning plain js. Also, since you are a beginner in programming, please point out any mistakes!
Ajax is also called asynchronous communication, and it is a process to change only the changed part of the screen without changing the screen. This reduces unnecessary rendering, shortens loading time, and allows users to use the service comfortably. By the way, synchronous communication redraws the entire screen, so even if the changed part is a part, the entire screen will be rendered. It can be a little stressful for the user.
Synchronous communication moves to the action of the specified controller when the deletion is done and looks for the action name.html.erb file. Asynchronous communication, on the other hand, is the same until the action of the specified controller is executed, after which it searches for the action name.js.erb file. Please be aware of the flow of these processes and try implementing after this.
<li><%= link_to 'Delete', category_path(category.id), method: :delete, remote: true, class:'category-destroy' %></li>
Add remote: true to the link_to description. With this alone, you can send a request from HTML format to JS format.
By adding remote: true, we will search for the js file. Furthermore, by using js.erb, you can embed the ruby grammar in the js description. This file is treated as a view file, so please store it in the corresponding views folder. I am passing the information I want to delete with querySelector ("# category- <% = @ category.id%>"). The specified target is being removed with .remove (). With these descriptions, you can erase certain elements in the view. By the way, even if you do not write js, it is deleted from the DB, but it will not disappear from the screen unless you reload it, so you need to write js.
app/views/categories/destroy.js.erb
(function(){
document.querySelector("#category-<%= @category.id %>").remove()
})();
This completes the deletion function by asynchronous communication! Asynchronous communication using rails is very easy to implement, so even beginners should definitely try it! I hope this article helps beginners. Please point out any mistakes!
Recommended Posts