【问题标题】:How does Devise hide some fields when output jsonDevise如何在输出json时隐藏一些字段
【发布时间】:2015-08-01 01:12:43
【问题描述】:

我正在使用 Grape + Mongoid + Devise。 当我编写 API 响应时,我发现 Devise 用户模型的字段(例如 encrypted_pa​​ssword、sign_in_count、last_sign_in_at)比用户 json 输出多。 我在Devise代码中搜索过,没有找到自定义to_json之类的东西,Devise是如何实现的?

【问题讨论】:

    标签: devise mongoid grape


    【解决方案1】:

    我不确定是否使用 Grape,但在 Rails 上,您可以使用 序列化器(因为 Grape 有许多与 Rails 兼容的代码,我认为有很大的工作机会)。

    要使用序列化程序,您需要包含“active_model_serializers”gem。

    例子:

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :email, :username
    end
    

    在此示例中,Devise 将始终在 JSON 输出中仅打印这 3 个字段。

    要包含除某些属性之外的所有属性,您可以执行以下操作:

    class UserSerializer < ActiveModel::Serializer
      attributes(*(User.attribute_names - ["date_created", "first_name"] ).map(&:to_sym))
    end
    

    此外,至少在 Rails 上,您需要从输出中删除根目录。为此,请将此代码添加到您的 application_controller.rb:

    def default_serializer_options  
      {root: false}  
    end  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2018-12-29
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      相关资源
      最近更新 更多