如何在 FastJsonAPI 中将参数从控制器传递到序列化程序?

How to pass parameters from controller to serializer in FastJsonAPI?

我有一个控制器方法 drop_down_values,其中我 select 一组值并在 json 中响应,使用序列化程序构建对象。我正在使用 FastJson Api。我想知道,如何访问序列化程序中控制器中存在的其他变量。

def drop_down_values   
    @drop_down_values = IndustrySectorList.all
    @values = @drop_down_values.pluck(:industry_sector)
    render json: DropDownValueSerializer.new(@drop_down_values).serialized_json
end

我需要在序列化程序中使用 @values 变量。我如何将其传递给序列化程序?我无法在序列化程序中直接访问此变量。

序列化器:

class DropDownValueSerializer
  include FastJsonapi::ObjectSerializer
  attributes :id
  end

堆栈和版本 -

  1. Rails - 5.2.1
  2. Ruby - 2.5.1
  3. FastJsonAPI - 1.5

如我所见,您应该像这样使用序列化方法: render json: DropDownValueSerializer.new(@drop_down_values).serialized_json

我不太确定您要做什么,但序列化程序通常是一种资源。在您的情况下,您可以将参数传递到下拉序列化程序中:

DropDownValueSerializer.new(movie, {params: {values: @values}})
class DropDownValueSerializer
  include FastJsonapi::ObjectSerializer
  attributes :id

  attribute :values do |drop_down_value, params|
    params[:values]
  end

end