我可能会为所有人使用不同的端点,但您也可以传入不同的 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
三种不同的序列化器:all、default、custom
全部
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