This article will discuss how to implement Ajax in a Rails 6 application. Here’s how to start:
1
2
3
rails new ajax
rails generate scaffold User name bio
rails db:create db:migrate
This will be the screen when you hit http://localhost:3000/users/new:
Go ahead and add a couple of users.
If you delete any of them now, this will not be an Ajax request, rather the page will be reloaded with the response. Let’s update it to use Ajax.
Create a file named destroy.js.erb in app/views/users/destroy.js.erb
.
1
touch app/views/users/destroy.js.erb
In app/views/users/destroy.js.erb
, put the following code:
1
2
3
$('.remove_user').bind('ajax:success', function() {
$(this).closest('tr').remove();
});
In app/views/users/index.html.erb
, make sure to delete the item that looks like this:
1
2
3
<td>
<%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' }, class: "remove_user", :remote => true %>
</td>
Make sure the destroy method in app/controllers/users_controller.rb
looks like this:
1
2
3
4
5
6
7
8
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
format.js { render :layout => false }
end
end
This implementation should delete the user with Ajax as long as jQuery is added in your application. If it isn’t, please follow this article to get it running.