yaru
yaru

Reputation: 1310

How to pass parameters to ActiveModel::ArraySerializer?

I need to have access to current_user_id from within ItemSerializer. Is there a way to achieve it? I am fine even with a dirty hack :)

I know about existence of serialization_options hash (from How to pass parameters to ActiveModel serializer ) but it works only with render command (if I am right) so it's possible to do:

def action
  render json: @model, option_name: value
end

class ModelSerializer::ActiveModel::Serializer
  def some_method
    puts serialization_options[:option_name]
  end
end

but in my case I use ArraySerializer to generate a json hash outside of render command like so:

positions_results = {}    
positions_results[swimlane_id][column_id] =
  ActiveModel::ArraySerializer.new(@account.items,
                                   each_serializer: ItemSerializer,
                                   current_user_id: current_user.id) # <---- Does not work

Upvotes: 6

Views: 6719

Answers (2)

Francesco Renzi
Francesco Renzi

Reputation: 547

You can do it in 2 ways:

  • Pass them through serialization_options, but as far as I know, and as you stated, you can only use it in a response from a controller:

  • Pass them through context or scope as you stated, and it's pretty much the same:

    # same as with scope 
    ActiveModel::ArraySerializer.new(@account.items, each_serializer: ItemSerializer, context: {current_user_id: 31337})
    
    # In serializer:
    class ItemSerializer < ActiveModel::Serializer
        attributes :scope, :user_id
    
        def user_id
          context[:current_user_id]
        end
    end
    

Upvotes: 10

yaru
yaru

Reputation: 1310

Basically the answer is here: https://github.com/rails-api/active_model_serializers/issues/510

ActiveModel::ArraySerializer.new(
                            @account.items,
                            each_serializer: ItemSerializer,
                            scope: {current_user_id: 31337})

and then in ItemSerializer:

class ItemSerializer < ActiveModel::Serializer
    attributes :scope, :user_id

    def user_id
      # scope can be nil
      scope[:current_user_id]
    end
end

Hope it helps anyone :)

Upvotes: 5

Related Questions