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

Default serializer render options in Rails controller


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?


Solution

  • 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]