【问题标题】:Apply filter to ActiveModel Serializer attributes to change the key将过滤器应用于 ActiveModel 序列化器属性以更改密钥
【发布时间】:2017-09-14 20:03:38
【问题描述】:

我的 rest API 有一个序列化程序。目前,它看起来像:

class TestSerializer < ActiveModel::Serializer
    attributes :id, :name, :field_one__c, :field_two__c
end

我想知道是否有任何方法可以过滤所有字段以在序列化时删除__c,如果有一种方法可以将逻辑应用于所有字段。

情况是我有很多最后带有__c 的字段,我想在序列化程序级别用最少的代码将它们全部删除。

【问题讨论】:

    标签: ruby-on-rails active-model-serializers


    【解决方案1】:

    是的,您可以使用 :key 选项在序列化程序中自定义属性 name

    attribute :field_one__c, key: :field_one
    attribute :field_two__c, key: :field_two
    

    您还可以使用:if:unless 选项使任何属性有条件

    文档:https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md#attribute


    更新:

    对于您的特殊情况,您可以通过在属性列表之前定义 attributes 类方法来解决此问题:

    class TestSerializer < ActiveModel::Serializer
      class << self
        def attributes(*attrs)
          attrs.each do |attr|
            options = {}
            options[:key] = attr.to_s[0..-4].to_sym if attr.to_s.end_with?('__c')
    
            attribute(attr, options)
          end
        end
      end
    
      attributes :id, :name, :field_one__c, :field_two__c
    end
    

    如果您有多个序列化程序类具有过滤大量属性的相同要求,您可以通过创建另一个继承自ActiveModel::Serializer 的序列化程序类来在您的解决方案中应用 DRY 原则。将上述类方法定义放在这个新的序列化程序中,并从这个新序列化程序继承所有序列化程序,这些序列化程序具有__c 的属性列表。

    class KeyFilterSerializer < ActiveModel::Serializer
      class << self
        def attributes(*attrs)
          attrs.each do |attr|
            options = {}
            options[:key] = attr.to_s[0..-4].to_sym if attr.to_s.end_with?('__c')
    
            attribute(attr, options)
          end
        end
      end
    end
    
    class TestSerializer < KeyFilterSerializer
      attributes :id, :name, :field_one__c, :field_two__c
    end
    
    class AnotherTestSerializer < KeyFilterSerializer
      attributes :id, :name, :field_one__c, :field_two__c
    end
    

    【讨论】:

    • 感谢您的回答!但是,我更想知道是否有一种方法可以将逻辑应用于所有字段。情况是我有很多最后带有__c 的字段,我想在序列化程序级别用最少的代码将它们全部删除。
    • 请查看更新,如果这是您正在寻找的东西,请告诉我:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    相关资源
    最近更新 更多