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

Active Model Serializer not responding with the correct attributes


I am working on a rails-api project where I am using active model serialiazer. But unfortunately its not working as expected. This is my V1::HuntsController

class V1::HuntsController < V1::MainController
  def index
    render json: Hunt.all
  end
end

My hunts serializer looks like this

class HuntSerializer < ActiveModel::Serializer
  belongs_to :user
  attributes :id,:title,:picture_url,:clue
  private
  def picture_url
    object.picture.url
  end
end

But in my response i am getting all the attributes from hunt. I tried to explicitly define serializer to avoid versioning issues as well.

render json: {data: Hunt.all } ,each_serializer: HuntSerializer

But nothing seems to work. In the logs I can see,

[active_model_serializers] Rendered V1::HuntSerializer with Hash (32.36ms)

Whats happening here. Any help would be appreciated.


Solution

  • try render json: Hunt.all, each_serializer: HuntSerializer (no need for data root)

    then to verify that the serializer gets hit, put a byebug in the body of the picture_url function. if the byebug gets hit, you are indeed using your serializer. (must have gem byebug included in gemfile)