I try to tell rails 3.2 that it should render JSON by default, and kick HTML completely like this:
respond_to :json def index @clients = Client.all respond_with @clients end
With this syntax, I have to add .json
to the URL. How can I achieve it?
Just call the library in whatever way/tech you are using and then append the result of the JSON data passed on to renderjson() function. It takes in the JSON you want to render as a single argument and returns an HTML element.
render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.
You can modify your routes.rb
files to specify the default format
routes.rb
resources :clients, defaults: {format: :json}
This will modify the default response format for your entire clients_controller
This pattern works well if you want to use the same controller actions for both. Make a web version as usual, using :html as the default format. Then, tuck the api under a path and set :json as the default there.
Rails.application.routes.draw do resources :products scope "/api", defaults: {format: :json} do resources :products end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With