[英]Active Model Serializer not working as expected
I've the folloing active model serializer but is not working as expected.我有以下活动模型序列化程序,但没有按预期工作。
gem 'active_model_serializers', '~> 0.10.x'
class UserSerializer < ActiveModel::Serializer
attributes :id
has_many :task
end
controller class method控制器类方法
def show
user = User.find(params[:id]);
render json:{status:'success', error:false, data:user},status: :ok
end
And model class和模型类
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
This gives the output这给出了输出
{
"status": "success",
"error": false,
"data": {
"id": 2,
"full_name": "sohail ahmad",
"email": "sohail1@gmail.com",
"created_at": "2020-03-10T05:41:42.045Z",
"updated_at": "2020-03-10T05:41:42.045Z"
}
}
How I get only Id with serializer.我如何使用序列化程序仅获取 Id。
Right now you are not using your UserSerializer in your controller.现在您没有在控制器中使用 UserSerializer。 Your show method should be like this in order to serialize its data.
你的 show 方法应该是这样的,以便序列化它的数据。
def show
user = User.find(params[:id]);
render json:{status:'success', error:false, data:UserSerializer.new(user)},status: :ok
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.