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

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

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

controller.rb

  1. respond_to do |format|
  2. if fields
  3. # less attributes : only a,c
  4. elsif xxx
  5. # default attributes
  6. else
  7. # all attributes : a,c,b,d,...
  8. end
  9. end

serializer.rb

  1. class WeatherLogSerializer < ActiveModel::Serializer
  2. attributes :id,:temperature
  3. def temperature
  4. "Celsius: #{object.air_temperature.to_f}"
  5. end
  6. end

解决方法

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

以下是我建议的方法

调节器

所有人的不同终点

  1. render json: objects,each_serializer: WeatherLogAllSerializer

允许自定义字段

  1. fields = params[:fields] # Csv string of specified fields.
  2.  
  3. # pass the fields into the scope
  4. if fields.present?
  5. render json: objects,each_serializer: WeatherLogCustomSerializer,scope: fields
  6. else
  7. render json: objects,each_serializer: WeatherLogSerializer
  8. end

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

所有

  1. class WeatherLogAllSerializer < ActiveModel::Serializer
  2. attributes :id,:temperature,:precipitation,:precipitation
  3. has_many :measurements
  4.  
  5. def temperature
  6. "Celsius: #{object.air_temperature.to_f}"
  7. end
  8. end

默认

  1. class WeatherLogSerializer < ActiveModel::Serializer
  2. attributes :id,:temperature
  3. def temperature
  4. "Celsius: #{object.air_temperature.to_f}"
  5. end
  6. end

习惯

  1. class WeatherLogCustomSerializer < WeatherLogSerializer
  2.  
  3. def attributes
  4. data = super
  5. if scope
  6. scope.split(",").each do |field|
  7. if field == 'precipitation'
  8. data[:precipitation] = object.precipitation
  9. elsif field == 'humidity'
  10. data[:humidity] = object.humidity
  11. elsif field == 'measurements'
  12. data[:measurements] = ActiveModel::ArraySerializer.new(object.measurements)
  13. end
  14. end
  15. end
  16. data
  17. end
  18. end

猜你在找的Ruby相关文章