ActiveRecord:返回对象时隐藏列

是否有一种开箱即用的方式来在返回ActiveRecord对象时始终隐藏/删除列(例如,User.password)? 谢谢。

使用内置序列化,您可以覆盖模型上的as_json方法以传递其他默认选项:

 class User < ActiveRecord::Base # ... def as_json(options = {}) super(options.merge({ except: [:password, :oauth_token] })) end end 

可能有更好的序列化工具 - 如果你正在寻找更细粒度的控制,我建议你查看active_model_serializersrabl

您可以使用:except在序列化时隐藏特定属性:except

 render json: @users, except: [:password, :other] 

或者,您可以使用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 

您是否因为试图隐藏纯文本密码而进入此页面?

停! 你做错了。

bug http://e-abaco.net/wp-content/uploads/2009/06/bug-feature.jpg

您不应该,永远不要将密码保存为纯文本。

有可能你的服务器已经或将会有某种缺陷,黑客会得到你的客户密码。 想一想:

  • 你会告诉他们什么?
  • 他们将如何反应?
  • 您的业​​务有哪些结果?

由于您现在是一个新人,正在搜索存储密码的正确方法,您可能想阅读这篇好文章