zak*_*ssi 13 activerecord ruby-on-rails ruby-on-rails-3 rails-activerecord
是否有一种开箱即用的方法可以在返回ActiveRecord对象时始终隐藏/删除列(例如,User.password)?谢谢.
Zac*_*emp 16
使用内置序列化,您可以覆盖as_json
模型上的方法以传递其他默认选项:
class User < ActiveRecord::Base
# ...
def as_json(options = {})
super(options.merge({ except: [:password, :oauth_token] }))
end
end
Run Code Online (Sandbox Code Playgroud)
可能有更好的序列化工具 - 如果你正在寻找更细粒度的控制我建议检查active_model_serializers
或rabl
.
停!你做错了.
bug http://e-abaco.net/wp-content/uploads/2009/06/bug-feature.jpg
您不应该,永远不要将密码保存为纯文本.
有可能你的服务器已经或将会有某种缺陷,黑客会得到你的客户密码.想一想:
由于您现在是一个新人,正在搜索存储密码的正确方法,您可能想阅读这篇好文章
您可以使用:except
以下命令在序列化时隐藏特定属性:
render json: @users, except: [:password, :other]
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用after_initialize
此方法,并将数据移动到非序列化属性中:
class User < ActiveRecord::Base
attr_accessor :hidden_password, :hidden_other
after_initialize :hide_columns
def hide_columns
[:password, :other].each do |c|
send("hidden_#{c}=", send(c))
send("#{c}=", nil)
end
end
end
Run Code Online (Sandbox Code Playgroud)