如何传递参数给ActiveModel::ArraySerializer?

How to pass parameters to ActiveModel::ArraySerializer?

我需要从 ItemSerializer 中访问 current_user_id。 有没有办法实现它?即使有一个肮脏的黑客我也很好:)

我知道 serialization_options 散列的存在(来自 How to pass parameters to ActiveModel serializer ) 但它只适用于 render 命令(如果我是对的)所以可以这样做:

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

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

但在我的例子中,我使用 ArraySerializerrender 命令之外生成一个 json 散列,如下所示:

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

基本上答案在这里: https://github.com/rails-api/active_model_serializers/issues/510

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

然后在 ItemSerializer:

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

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

希望对大家有所帮助:)

您可以通过两种方式完成:

  • 通过 serialization_options 传递它们,但据我所知,正如您所说,您只能在控制器的响应中使用它:

  • 按你说的contextscope传递给他们,几乎是一样的:

    # 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