如何覆盖'as_json'或'to_json'方法以使'respond_to'不包含指定信息? [英] How to override the 'as_json' or 'to_json' method in order to 'respond_to' without including specified information?

查看:163
本文介绍了如何覆盖'as_json'或'to_json'方法以使'respond_to'不包含指定信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ruby on Rails 3,并且想覆盖as_jsonto_json方法(可能在模型文件中),以便respond_to HTTP请求而不包含某些信息.

I am using Ruby on Rails 3 and I would like to override (possibly in the model file) the as_json or to_json method in order to respond_to an HTTP request without including some information.

我的帐户模型我有

def as_json(options = {})
  super(
    :except => [
      :password
    ]
  )
end

在我的控制器中,

format.json {
  render :json => @account, :status => 200
}

例如,当我向/account/1.json发出请求时,出于安全原因,我还获得了我不想要的密码属性.

When I make a request, for example, to /account/1.json I have back also the password attributes that, for security reasons, I don't want.

因此,如何防止包含指定信息?

我可以做到,而且可以正常工作

I can do this and it works

format.json {
  render :json => @account.to_json(:except => [:password]), :status => 200
}

但是我需要重构.

推荐答案

如果仅执行一项操作,则可以尝试:

If it is only in one action you can try:

format.json { render :json => @account, :except => :password }

如果您需要一项以上的操作,则优先于覆盖操作会更好:

if you need it for more than one action than the override would be better:

# Exclude password info from json output.
def to_json(options={})
  options[:except] ||= :password
  super
end 

as_json同样有用

the same is good for as_json

# Exclude password info from json output.
def as_json(options={})
  options[:except] ||= :password
  super
end

这篇关于如何覆盖'as_json'或'to_json'方法以使'respond_to'不包含指定信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆