简体   繁体   中英

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.

Right now you are not using your UserSerializer in your controller. Your show method should be like this in order to serialize its data.

def show
    user = User.find(params[:id]);
    render json:{status:'success', error:false, data:UserSerializer.new(user)},status: :ok
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM