【发布时间】:2015-08-01 01:12:43
【问题描述】:
我正在使用 Grape + Mongoid + Devise。 当我编写 API 响应时,我发现 Devise 用户模型的字段(例如 encrypted_password、sign_in_count、last_sign_in_at)比用户 json 输出多。 我在Devise代码中搜索过,没有找到自定义to_json之类的东西,Devise是如何实现的?
【问题讨论】:
我正在使用 Grape + Mongoid + Devise。 当我编写 API 响应时,我发现 Devise 用户模型的字段(例如 encrypted_password、sign_in_count、last_sign_in_at)比用户 json 输出多。 我在Devise代码中搜索过,没有找到自定义to_json之类的东西,Devise是如何实现的?
【问题讨论】:
我不确定是否使用 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
【讨论】: