Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 381
yaru Avatar asked Sep 07 '15 13:09

yaru


2 Answers

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
    
like image 58
Francesco Renzi Avatar answered Nov 01 '22 06:11

Francesco Renzi


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 :)

like image 40
yaru Avatar answered Nov 01 '22 07:11

yaru