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.

http://brettu.com/rails-ruby-tips-230-pass-options-to-activemodelserializers/
http://stackoverflow.com/questions/23347587/how-to-pass-parameters-to-activemodel-serializer

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 https://github.com/rails-api/active_model_serializers/blob/v0.9.0/lib%2Factive_model%2Fserializer.rb#L139

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 https://web.archive.org/web/20140601170936/https://github.com/rails-api/active_model_serializers, 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