[英]to_json with conditional :except in rails
我有一个带有id,name和url属性的User模型以及一个带有id和show_my_url字段的关联Preferences模型。
我想将我的用户渲染为json,但如果user.preferences.show_my_url为'true',则只包含url属性。
如何根据首选项删除用户url属性,以便它不包含在to_json呈现中。
def to_json(opts={})
except = [] # Standard except, may contain some stuff you want to exclude
except << :url unless self.preferences.show_my_url
super(opts.merge(:except => except))
end
我认为您正在寻找的是Serializer: ActiveRecord中的JSON Serializers 。 这是正确的方法。
所以为了你的问题,你可以在你的用户类上实现这样的东西:
def as_json
preferences.try(:show_my_url) ? to_json : to_json(:except => :url)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.