开发者

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 i开发者_StackOverflownformation.

  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.


Use the :methods option to to_json.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜