ActiveRecord的:隐藏列,而返回的对象 [英] ActiveRecord : Hide column while returning object
本文介绍了ActiveRecord的:隐藏列,而返回的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种即开即装即用的方式来始终隐藏/删除列(比方说,user.password的),而返回一个ActiveRecord对象? 谢谢你。
Is there an out-of-the-box way to always hide/remove a column (say, User.password) while returning an ActiveRecord object ? Thanks.
推荐答案
使用内置的序列化,你可以覆盖 as_json
方法对你的模型传递更多默认选项:
Using the built-in serialization, you can override the as_json
method on your model to pass in additional default options:
class User < ActiveRecord::Base
# ...
def as_json(options = {})
super(options.merge({ except: [:password, :oauth_token] }))
end
end
有可能是更好的序列化工具,有 - 如果你正在寻找更细粒度的控制,我会建议检查出 active_model_serializers
或 Rabl的
。
There are probably better serialization tools out there - if you are looking for more fine-grained control I would recommend checking out active_model_serializers
or rabl
.
这篇关于ActiveRecord的:隐藏列,而返回的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文