Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 635
Rick Avatar asked Jun 24 '26 12:06

Rick


1 Answers

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]

like image 138
Rick Avatar answered Jun 26 '26 03:06

Rick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!