8

I am using Ruby on Rails 3 and I would like to override the to_json method.

At this time I use the following code in order to avoid to export important information.

  def to_json
    super(
      :except => [
        :password
      ]
    )
  end

If I want change a value using that method, how I can do?

For example, I would like to capitalize the user name

:name => name.capitalize

on retrieving this

@user.to_json
user502052
  • 14,803
  • 30
  • 109
  • 188
  • Similar problem here, could be helpful. http://stackoverflow.com/questions/4703509/how-to-customize-the-to-json-method-in-rails3 – lashleigh Mar 01 '11 at 21:18

2 Answers2

12

If you want to render :json => @user in the controller for Rails 3, you can override as_json in the model:

class User < ActiveRecord::Base
  def as_json(options={})
    result = super({ :except => :password }.merge(options))
    result["user"]["name"] = name.capitalize
    result
  end
end

Here's a good post about the differences between to_json and as_json.

zetetic
  • 47,184
  • 10
  • 111
  • 119
  • 1
    FWIW, when calling `user.to_json`, in Rails 3.1.3, I was seeing the `as_json` receiving `nil` for the options argument, so I added `options ||= {}` as the first line of my custom `as_json` method. – Jeremy Weathers Apr 12 '12 at 03:03
0

Use the :methods option to to_json.

http://apidock.com/rails/ActiveRecord/Serialization/to_json

rmk
  • 4,395
  • 3
  • 27
  • 32
  • I need a `def to_json ...` (in my model) and not `konata.to_json(:methods => :permalink)` (in controller or anywhere else) – user502052 Mar 01 '11 at 21:13
  • Oh, so you want to override the default to_json? That is fine, I think. – rmk Mar 01 '11 at 21:19
  • I tryed multiple tests, but I was getting always errors. Please, can you make me a working example? – user502052 Mar 01 '11 at 21:21
  • I think the problem linked here by Iashleigh is useful. If you are using Rails3, you should probably override as_json, as mentioned there. – rmk Mar 01 '11 at 21:26