Search code examples
ruby-on-railsjsonrubyactive-model-serializers

active model serializers rails json doesnt work inside another json object


iam using active model serializers in my rails, this is my snippet

# GET /users
  def index
    @users = User.all
    render json: {data: @users, status: httpstatus[:getSuccess]}
    # render json: {data: @users, status: httpstatus[:getSuccess]}
  end

but its showing like this in postman

"data": [
{
  "id": 38,
  "name": "tyasa",
  "age": 21,
  "created_at": "2017-05-30T06:23:03.504Z",
  "updated_at": "2017-05-30T06:23:03.504Z"
},
{
  "id": 39,
  "name": "wahyu",
  "age": 21,
  "created_at": "2017-05-30T06:23:37.359Z",
  "updated_at": "2017-05-30T06:23:37.359Z"
},]

but its work when just render the @users

# GET /users
  def index
    @users = User.all
    render json: {data: @users, status: httpstatus[:getSuccess]}
    # render json: @users
  end

i just wanna delete created at and update at from the json. How to solve this.. sory bad english


Solution

  • I just wanna delete created at and update at from the json.

    You can use except option of as_json

    render json: {data: @users.as_json(:except => [:created_at, :updated_at]), status: httpstatus[:getSuccess]}
    

    which should give you

    "data": [
    {
      "id": 38,
      "name": "tyasa",
      "age": 21
    },
    {
      "id": 39,
      "name": "wahyu",
      "age": 21
    },]