Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to override to_json in Rails?
    text
    copied!<hr> <h1>Update:</h1> <p>This issue was not properly explored. The real issue lies within <code>render :json</code>.</p> <p>The first code paste in the original question will yield the expected result. However, there is still a caveat. See this example:</p> <p><code>render :json =&gt; current_user</code></p> <p>is <strong>NOT</strong> the same as</p> <p><code>render :json =&gt; current_user.to_json</code></p> <p>That is, <code>render :json</code> will not automatically call the <code>to_json</code> method associated with the User object. <em>In fact</em>, if <code>to_json</code> is being overridden on the <code>User</code> model, <code>render :json =&gt; @user</code> will generate the <code>ArgumentError</code> described below.</p> <h2>summary</h2> <pre><code># works if User#to_json is not overridden render :json =&gt; current_user # If User#to_json is overridden, User requires explicit call render :json =&gt; current_user.to_json </code></pre> <p>This all seems silly to me. This seems to be telling me that <code>render</code> is not actually calling <code>Model#to_json</code> when type <code>:json</code> is specified. Can someone explain what's really going on here?</p> <p>Any genii that can help me with this can likely answer my other question: <a href="https://stackoverflow.com/questions/2572340/how-to-build-a-json-response-by-combining-foo-to-jsonoptions-and-bars-to-json">How to build a JSON response by combining @foo.to_json(options) and @bars.to_json(options) in Rails</a></p> <hr> <h1>Original Question:</h1> <p>I've seen some other examples on SO, but I none do what I'm looking for.</p> <p>I'm trying:</p> <pre><code>class User &lt; ActiveRecord::Base # this actually works! (see update summary above) def to_json super(:only =&gt; :username, :methods =&gt; [:foo, :bar]) end end </code></pre> <p>I'm getting <code>ArgumentError: wrong number of arguments (1 for 0)</code> in </p> <pre><code>/usr/lib/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/json/encoders/object.rb:4:in `to_json </code></pre> <p>Any ideas?</p>
 

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