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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With