ruby-on-rails-4 – 如何在Active Model Serializers上动态添加
发布时间:2020-12-16 21:15:46 所属栏目:百科 来源:网络整理
导读:我想决定在我的控制器中输出的属性数量. 但我不知道必须这样做吗? 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 Weath
我想决定在我的控制器中输出的属性数量.
但我不知道必须这样做吗? 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |