Passing options to active_model_serializers

I’m having trouble passing in options to my active_model_serializers. I found two posts that make it seem like you can do this.

I can’t get it to work. My serializers don’t seem to have any reference to options or @options. Does this feature still exist in 0.9.0?

I haven’t upgraded my project to 0.9.0 yet. I’m still using 0.8.2. As far I see on this line active_model_serializers/serializer.rb at v0.9.0 · rails-api/active_model_serializers · GitHub

So you probably could do:

render json: @user, context: { winner: false, active: true }

# app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
  attributes :winner, :active
 
  def winner
    context[:winner]
  end
 
  def active
    context[:active]
  end
end

I haven’t tested myself yet :smile:

Do not use 0.9. The original master README (now gone, but can be seen here rails-api/active_model_serializers · GitHub, read under Master - 0.9.0) for this version had the @options hash removed. The next release is supposed to bring that back.

@samnang you were correct with your response. However, context does not apply to the associations which is something I need.

@frank_west_iii I think this would explain why using active model serializers has been such a struggle so far. Following your advice has allowed me to use @options which solves my issues. Thanks!

Hey Nicolo,

I was just wondering how you managed to get @options working in your situation?

I’m current;y using grape api with active model serializers 0.9.3 and can’t see to pass in some custom options to my serializer.

Thanks,
Tom