First let’s create a new Rails application. We’ll call it ajaxstore.
Now let’s create some scaffolding and take a look at how it works.
Now let’s download jQuery.
Open up routes.rb – we need to add an option to the products resource route. I’m using delete as my option. You could overload destroy but in my opinion that makes the destroy action less cohesive.
We now need to add a view for our new action. Create a new file named ‘delete.html.erb’ in your product views directory. We’ll keep it fairly simple, and ask the user to confirm the destroy.
At this point we need to do some refactoring. Open up the Products controller and look at all the places we’re calling Product.find(params[:id]). We’re going to refactor that into a before filter and simplify the controller a bit. Here’s the entire controller.
Here we removed the edit and show actions, removed the first line from the update and destroy actions, created a method to load the product, and finally setup the filter. Now lets change how we generate our destroy links in the index and show views. First open up the Product index view and change the destroy link (should be around line 15) to this.
We also need to make some changes to our CSS file – here are the styles we need to add.
Let’s get Rails setup to do some ajax’n. There are a couple changes you need to make to every application. Add these lines under the protect_from_forgery line in your application controller.
And under those lines add the corresponding methods:
The set_xhr_flash method removes the flash if the current request is an ajax request. If we don’t clear the flash on an ajax request the next time the user makes a full http request the user will see the flash message. The other method is for safari and IE browsers – we’re correcting some headers for ajax requests. One last change to our destroy action in our Products controller and we’re good to go.