如何在创建设计用户时自定义 JSON 输出?
### User.rb ###
class User < ActiveRecord::Base
devise :database_authenticatable,
:registerable, ...
...
end
### Routes.rb ###
...
devise_for :users, :controllers => {:registrations => "registrations"}
...
我的用户表中有一些额外的字段是秘密的,但是当我通过 JSON 进行用户创建时,它们会在 JSON 响应中返回,如下所示:
$ curl -H "Content-Type: application/json" -d '{"user" : {"username":"someone","email":"someone@somewhere.com","password":"awesomepass"}}' -X POST http://localhost:3000/users.json
返回:
{"user":{"secret_field_1":"some value","secret_field_2":"some value","created_at":"2013-07-25T21:24:50-05:00","email":"someone@somewhere.com","first_name":null,"id":3226,"last_name":null,"updated_at":"2013-07-25T21:24:50-05:00","username":"someone"}}
我想隐藏那些秘密字段,但不知道如何自定义 JSON 响应。
我试过一个标准的 ActiveRecord 序列化器:
class UserSerializer < ActiveModel::Serializer
attributes :id, :created_at, :updated_at, :email, :first_name, :last_name, :username
end
无济于事,我猜是因为设计。