【问题标题】:to_json with conditional :except in rails带条件的 to_json :除了在 r​​ails 中
【发布时间】:2023-03-09 07:43:01
【问题描述】:

我有一个带有 id、name 和 url 属性的 User 模型和一个带有 id 和 show_my_url 字段的关联 Preferences 模型。

我想将我的用户呈现为 json,但仅在 user.preferences.show_my_url 为“true”时才包含 url 属性。

如何根据首选项删除用户 url 属性,使其不包含在 to_json 渲染中。

【问题讨论】:

  • 如果不需要默认方法,最简单的方法是重载to_json 方法

标签: ruby-on-rails ruby json


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    我认为您正在寻找的是序列化程序:JSON Serializers in ActiveRecord。这是正确的做法。

    所以对于你的问题,你可以在你的用户类上实现这样的东西:

    def as_json
      preferences.try(:show_my_url) ? to_json : to_json(:except => :url)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多