With Rails ‘respond_to’ method, it is really easy to return differnt kinds of data from the same controller method based on the url extension. I was really happy with this when I was building a a site to provide a read-only version of an event calendar I had built years earlier on the ArsDigita Community System. To get data out of that Oracle database, I built a Rails web site that let users ask for events by category, sponsor, or lecture series with a variety of date restrictions. The data was consumed by several different clients - two who wanted XML and several others who wanted JSON. I could use exactly the same URLs by just adding .xml or .json to the url. Even better, I could have controller render an html version of the same data which developers could use to preview the result sets. Once they had all the parameters the way they wanted, they just copied the url and added ‘.json’ ahd used it in their web pages.
First, the regular form_for helper:
But with ‘remote: true’ (note no authenticity_token):
This comes into the server and is interpretted as a JS request:
which will fall into the format.js case in the normal respond_to stanza, which by default, will try to render the create.js.erb template in your courses views. This view should jquery directives that will be executed in the browser.
So to correct that, we add a ‘format.json’ section to our ‘respond_to’ block: