在我的控制器中我目前有:
invite = Invite.find_by_token(params[:id])
user = invite.user
json_response({
user: user
})
def json_response(object, status = :ok)
render json: object, status: status
end
现在,用户正在返回所有用户字段。我想回复(身份证,电子邮件)......我试过了:
user = invite.user.select(:id, :email)
user = invite.user.pluck(:id, :email)
既不起作用。想法?
答案 0 :(得分:3)
您可以使用方法as_json在响应中传递所需的属性,例如:
user.as_json(only: [:id, :email])
答案 1 :(得分:2)
我知道这个问题已经有了答案,但也有一个很好的宝石可以使用,称为active_model_serializers。这使您可以在JSON输出中为不同的模型准确指定所需的属性,甚至可以在响应中包含与其他模型的关系。
的Gemfile:
gem 'active_model_serializers', '~> 0.10.0'
然后运行bundle install
。
然后,您可以使用generator命令创建序列化程序:
rails g serializer user
将在project-root/app/serializers/
。
在序列化程序中,您可以将所需的属性列入白名单:
<强>项目根/应用/串行化器/ user_serializer.rb 强>:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
end
现在,只要您返回User
个对象,它就只会输出这两个属性id
和email
。
想要打印出相关型号吗?简单。您只需在序列化程序中添加关系,它就会在JSON输出中包含这些相关模型。
假装用户&#34;有很多&#34;帖子:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :posts
end
现在您的JSON输出应该类似于:
{
"id": 1,
"email": "user@example.com",
"posts": [{
id: 1,
title: "My First Post",
body: "This is the post body.",
created_at: "2017-05-18T20:03:14.955Z",
updated_at: "2017-05-18T20:03:14.955Z"
}, {
id: 2,
title: "My Second Post",
body: "This is the post body again.",
created_at: "2017-05-19T20:03:14.955Z",
updated_at: "2017-05-19T20:03:14.955Z"
},
...
]
}
非常整洁方便。如果你想限制帖子只打印某些列,你需要做的就是为posts
创建一个序列化器,指定属性,输出就可以了。