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

yar*_*aru 6 active-model-serializers ruby-on-rails-4

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

我知道serialization_options哈希的存在(从如何将参数传递给ActiveModel序列化程序 ),但它只适用于render命令(如果我是对的),所以可以这样做:

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

class ModelSerializer::ActiveModel::Serializer
  def some_method
    puts serialization_options[:option_name]
  end
end
Run Code Online (Sandbox Code Playgroud)

但在我的情况下,我ArraySerializer用来生成render命令之外的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
Run Code Online (Sandbox Code Playgroud)

Fra*_*nzi 8

你可以用两种方式做到:

  • 通过它们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
    
    Run Code Online (Sandbox Code Playgroud)


yar*_*aru 5

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

ActiveModel::ArraySerializer.new(
                            @account.items,
                            each_serializer: ItemSerializer,
                            scope: {current_user_id: 31337})
Run Code Online (Sandbox Code Playgroud)

然后在ItemSerializer:

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

    def user_id
      # scope can be nil
      scope[:current_user_id]
    end
end
Run Code Online (Sandbox Code Playgroud)

希望它能帮到任何人:)