Here is a small application which is basically a scaffold but create, edit, update and destroy are done using ajax ie remote => true option in rails. See Demo.
So the very first thing is understand repond_to block. If you run a scaffold command and see new action code it looks like:
which means this will respond to only two kinds of request one is HTML and second is json.
Now for your-your ajax request your need to tell the controller to respond to js request which can be done but adding a line i.e.,.
Now you have told the controller to send the response for js request. Create a file ie new.js.erb. This is the file where you write some js code to make the response to do the desired stuff.
Cool. Let’s start from scratch.
Step 1: Make a new application Step 2: Generate a scaffold Step 3: Start making the js requests and add some code to get desired results.
Create an application and generate a scaffold ie:
Once You have it. Make a js requests for new link from index.html.erb ie:
Now enable js requests in the controller for new action ie:
Now create a new.js.erb file in products directory and add this line of code:
This will hide the new_product_link and add a new product form. Hit refresh of you index page and try to click on new product link. ;)
Now if you try to submit the form, it will be submitted as normal form. To make it ajax. Modify the form like this:
Now refresh and try to submit the form. The form will be submitted, but the request is not handled properly on controller end. Here is the same code for create action.
Hey hey.. Before you try to submit the form. Modify your index.html.erb like this so that you can render a product row in index.html.erb.
and a product.html.erb partial ie _product.html.erb
Once you make this modification. You can see that rendering a new form and create a new product is completely Ajaxified. In the same way, you can do for edit form and update and for destroy.
Source code: Clone this repo to see the whole code
This is how you can do a lot of things to Ajaxify your site with respond_to and remote => true.
Do check out how to add validations in ajax based forms