Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rails controller generators implement JSON responses by default.</p> <p>For example, if you have this method:</p> <pre><code>class UsersController &lt; ApplicationController def index @users = User.all end end </code></pre> <p>You could add JSON response like so</p> <pre><code>class UsersController &lt; Application Controller def index respond_to do |format| format.html format.js { render :json =&gt; @users } end end end </code></pre> <p>Now, you have two responses for <code>/users</code></p> <ol> <li><code>http://someapp.com/users</code></li> <li><code>http://someapp.com/users.json</code></li> </ol> <hr> <p>You can add another one very easily; e.g.,</p> <pre><code>format.xml { render :xml =&gt; @users } </code></pre> <p>Now your app will respond to <code>http://someapp.com/users.xml</code></p> <hr> <h3>Customizing your json</h3> <p>Chances are you won't want to output all the fields of a table in your json. For that, look to <a href="https://github.com/rails/jbuilder" rel="noreferrer"><code>rails/jbuilder</code></a>. It lets you create JSON structures with a builder-style DSL.</p> <p>An example from the jbuilder README</p> <pre><code>Jbuilder.encode do |json| json.content format_content(@message.content) json.(@message, :created_at, :updated_at) json.author do json.name @message.creator.name.familiar json.email_address @message.creator.email_address_with_name json.url url_for(@message.creator, format: :json) end if current_user.admin? json.visitors calculate_visitors(@message) end json.comments @message.comments, :content, :created_at json.attachments @message.attachments do |attachment| json.filename attachment.filename json.url url_for(attachment) end end </code></pre> <p>Produces the following output:</p> <pre><code>{ "content": "&lt;p&gt;This is &lt;i&gt;serious&lt;/i&gt; monkey business", "created_at": "2011-10-29T20:45:28-05:00", "updated_at": "2011-10-29T20:45:28-05:00", "author": { "name": "David H.", "email_address": "'David Heinemeier Hansson' &lt;david@heinemeierhansson.com&gt;", "url": "http://example.com/users/1-david.json" }, "visitors": 15, "comments": [ { "content": "Hello everyone!", "created_at": "2011-10-29T20:45:28-05:00" }, { "content": "To you my good sir!", "created_at": "2011-10-29T20:47:28-05:00" } ], "attachments": [ { "filename": "forecast.xls", "url": "http://example.com/downloads/forecast.xls" }, { "filename": "presentation.pdf", "url": "http://example.com/downloads/presentation.pdf" } ] } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload