ruby-on-rails-4 – 如何在Active Model Serializers上动态添加属性

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-4 – 如何在Active Model Serializers上动态添加属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想决定在我的控制器中输出属性数量.

但我不知道必须这样做吗?

controller.rb

respond_to do |format|
    if fields
      # less attributes : only a,c
    elsif xxx
      # default attributes
    else
      # all attributes : a,c,b,d,...
    end
  end

serializer.rb

class WeatherLogSerializer < ActiveModel::Serializer
  attributes :id,:temperature
  def temperature
    "Celsius: #{object.air_temperature.to_f}"
  end
end

解决方法

我可能会为所有人使用不同的端点,但您也可以传入不同的url参数或类似的东西.通常情况下,我认为您希望默认值更加有限.

以下是我建议的方法

调节器

所有人的不同终点

render json: objects,each_serializer: WeatherLogAllSerializer

允许自定义字段

fields = params[:fields] # Csv string of specified fields.

# pass the fields into the scope
if fields.present?
  render json: objects,each_serializer: WeatherLogCustomSerializer,scope: fields
else
  render json: objects,each_serializer: WeatherLogSerializer
end

三种不同的序列化器:全部,默认,自定义

所有

class WeatherLogAllSerializer < ActiveModel::Serializer
  attributes :id,:temperature,:precipitation,:precipitation
  has_many :measurements

  def temperature
    "Celsius: #{object.air_temperature.to_f}"
  end
end

默认

class WeatherLogSerializer < ActiveModel::Serializer
  attributes :id,:temperature
  def temperature
    "Celsius: #{object.air_temperature.to_f}"
  end
end

习惯

class WeatherLogCustomSerializer < WeatherLogSerializer

  def attributes
    data = super
    if scope
      scope.split(",").each do |field|
        if field == 'precipitation'
          data[:precipitation] = object.precipitation
        elsif field == 'humidity'
          data[:humidity] = object.humidity
        elsif field == 'measurements'
          data[:measurements] = ActiveModel::ArraySerializer.new(object.measurements)
        end
      end
    end
    data
  end
end
原文链接:https://www.f2er.com/ruby/267744.html

猜你在找的Ruby相关文章