Question

Damn, that's me again...

Quote from RocketPants git:

Support for active_model_serializers - If you want to use ActiveModelSerializers, we'll take care of it. Even better, in your expose call, pass through :serializer as expected and we'll automatically take care of invoking it for you.

So that's what I try to do:

def friends
    @user = User.find_by_id(params[:id])
    expose @user.friends.first(params[:limit].to_i), serializer: UserJustNameSerializer
end

And that's how I implement my serializers in user_serializer.rb:

class UserSerializer < ActiveModel::Serializer
....
end

class UserJustNameSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :full_name, :avatar_thumb

  def avatar_thumb
    object.avatar.url(:thumb)
  end
end

Using expose without serializer option is properly preparing JSON according to UserSerializer. Trying to use UserJustNameSerializer gives this error:

NameError (uninitialized constant Api::V1::UsersController::UserJustNameSerializer)

So the question is: how to properly show RocketPants the way to my serializer? Now it's trying to find it in UsersController.

Was it helpful?

Solution

So, as always, only after posting the question I get to answer =)

The solution is: Place UserJustNameSerializer into its own file user_just_name_serializer.rb and use each_serializer: instead of serializer:, as I'm trying to serialize an array, not a single object.

For those who google: If I use serializer: UserJustNameSerializer on array, I get

NoMethodError (undefined method `read_attribute_for_serialization' for []:Array):
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top