Skip to content

Instantly share code, notes, and snippets.

@fokayx
Created June 30, 2015 05:00
Show Gist options
  • Select an option

  • Save fokayx/bc46903d4f0dfc97b21e to your computer and use it in GitHub Desktop.

Select an option

Save fokayx/bc46903d4f0dfc97b21e to your computer and use it in GitHub Desktop.
About JSON. How to use rails format.json?@stackoverflow.

How to use rails format.json? @Stackoverflow

def index
	@cellphones = Cellphone.all

	respond_to do |format|
	format.html
	format.json { render json: @cellphoes }
end
  • what is format.json used for?
  • do I have to create a view for it?
  • how does it relate to javascrip?
  • how does it relate to ajax?
  • please give a simple example of how to use it...
  1. It's used to return JSON.
  2. No, it renders @cellphones as JSON. You may create a view, though, for example, using a JSON builder to customize the output beyond what Rails provides out of the box.
  3. JavaScript is often used to make JSON Ajax requests, like for client-side frameworks.
  4. Ajax calls often want JSON as a result. They may also request HTML to render directly.
  5. That is an example of how to use it; make an Ajax request to /cellphones.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment