Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a few options.</p> <p>You can overwrite the <code>as_json</code> method on the model you are working with <a href="http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/" rel="nofollow">http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/</a></p> <p>You can use a json builder<br> <a href="https://github.com/rails/jbuilder" rel="nofollow">jbuilder</a><br> <a href="https://github.com/nesquena/rabl" rel="nofollow">rabl</a></p> <p>You could create a serializer<br> <a href="http://railscasts.com/episodes/409-active-model-serializers" rel="nofollow">http://railscasts.com/episodes/409-active-model-serializers</a></p> <p>or you could use the <code>:only</code> option on <code>to_json</code></p> <pre><code>def index @models = Model.all respond_with(@models) do |format| format.html { render } format.json { render json: @models.to_json( only: [:some_attribute, :some_other_attribute] ) } end end </code></pre> <p>Unless you are using these constraints in many actions I would recommend the last choice (using <code>:only</code> because I believe it to be the simplest but you may feel like the controller isn't the place for this kind of logic.</p> <p>And there are probably many more ways to do this.</p> <p><strong>Edit</strong>:<br> <code>respond_with</code> takes a hash as a second argument to make the above prettier (thanks @ck3g)</p> <pre><code>def index @models = Model.all respond_with @models, only: [:some_attribute, :some_other_attribute] end </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