How to pass parameters from controller to serializer in FastJsonAPI?

3.4k Views Asked by At

I have a controller method drop_down_values in which I select a set of values and respond in json ,building the object using a serializer. I am using FastJson Api. I want to know , how can I access other variables present in the controller in the serializer.

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

I need to use the @values variable in the serializer. How can i pass this to serializer? I am not able to directly access this variable in the serializer.

Serializer:

class DropDownValueSerializer
  include FastJsonapi::ObjectSerializer
  attributes :id
  end

Stack & version -

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

There are 2 best solutions below

0
On BEST ANSWER

I'm not really sure what you are trying to do but a serializer is usually a resource. In your case you can pass params into your drop down serializer :

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

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

end

3
On

As I can see, you should use the serialized method like this: render json: DropDownValueSerializer.new(@drop_down_values).serialized_json