Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 如何将参数传递给ActiveModel::ArraySerializer?_Ruby On Rails 4_Active Model Serializers - Fatal编程技术网

Ruby on rails 4 如何将参数传递给ActiveModel::ArraySerializer?

Ruby on rails 4 如何将参数传递给ActiveModel::ArraySerializer?,ruby-on-rails-4,active-model-serializers,Ruby On Rails 4,Active Model Serializers,我需要从ItemSerializer中访问当前用户\u id。 有没有办法做到这一点?即使有一个肮脏的黑客,我也很好:) 我知道存在serialization\u选项hash(来自 )但它仅适用于render命令(如果我是对的),因此可以执行以下操作: def action render json: @model, option_name: value end class ModelSerializer::ActiveModel::Serializer def some_method

我需要从ItemSerializer中访问
当前用户\u id
。 有没有办法做到这一点?即使有一个肮脏的黑客,我也很好:)

我知道存在
serialization\u选项
hash(来自 )但它仅适用于
render
命令(如果我是对的),因此可以执行以下操作:

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

class ModelSerializer::ActiveModel::Serializer
  def some_method
    puts serialization_options[:option_name]
  end
end
但在我的例子中,我使用
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
positions_results={}
位置结果[泳道id][栏id]=
ActiveModel::ArraySerializer.new(@account.items,
每个_序列化程序:ItemSerializer,

current_user_id:current_user.id)#基本上答案如下:

然后在
ItemSerializer
中:

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

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

希望它对任何人都有帮助:)

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

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

  • 如您所述,通过
    上下文
    范围
    传递它们,它们基本相同:

    # 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
    
    #与作用域相同
    ActiveModel::ArraySerializer.new(@account.items,每个序列化程序:ItemSerializer,上下文:{current_user_id:31337})
    #在序列化程序中:
    类ItemSerializer
# 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