3

I am using Active Model Serializers in a rails project and have a user object that needs to be passed in from the controller to the serializer like this:

# Note the 'user:' option that will be accessible inside
# the serializer with @options[:user]
def show
render json: @some_object, user: current_user
end

def index
render json: SomeObject.all, user: current_user
end

This is good enough for what I am trying to do, but it is not very DRY and results in render statements that are littered with options. When those options change, I need to go back and manually remove/modify them across all actions.

My question is: Is there a way to set a list of default options for a render call at the controller level, instead of manually putting the options in every single controller action?

Rick
  • 8,366
  • 8
  • 47
  • 76

1 Answers1

3

This can be accomplished by adding this method to your controller:

def default_serializer_options  
  {user: current_user}  
end

You can then access it from within the serializer via options[:user]

Rick
  • 8,366
  • 8
  • 47
  • 76