How to change values ​​overriding 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 to avoid exporting important information.

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

If I need to change a value using this method, how can I do this?

For example, I would like to use a username

 :name => name.capitalize 

when retrieving this

 @user.to_json 
+6
json override ruby ruby-on-rails ruby-on-rails-3
source share
2 answers

If you want 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 is a good post on the differences between to_json and as_json .

+10
source share

Use the :methods parameter for to_json .

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

0
source share

All Articles