Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change values overriding the 'to_json' method?

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
like image 883
user502052 Avatar asked Mar 01 '11 20:03

user502052


1 Answers

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.

like image 78
zetetic Avatar answered Sep 20 '22 10:09

zetetic