【问题标题】:ActiveModel::Serializer define attribute attributes?ActiveModel::Serializer 定义属性属性?
【发布时间】:2016-01-07 14:22:02
【问题描述】:

我正在尝试为我的 Rails 应用程序实现 JSON API。它需要定义attributes 字段。但是ActiveModel::Serializer 有一个同名的方法,因此

class FooSerializer < ActiveModel::Serializer
  attributes :attributes

  def attributes
    {
      # to be filled
    }
  end
end

只会覆盖原来的方法。是否有可能以某种方式添加 attributes 字段?

【问题讨论】:

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


    【解决方案1】:

    ActiveModel Serializer 支持开箱即用的 JSON API。您只需要设置正确的适配器。

    ActiveModelSerializers.config.adapter = :json_api
    

    https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/adapters.md

    【讨论】:

    • 它生成一个 JSON 对象,但不创建属性容器。
    • 您使用的是哪个版本的 AMS。你也可以显示 AMS 初始化文件
    • 我使用 AMS v 0.9.3 config/initializers/active_model_serializer.rb ruby ActiveModel::Serializer.setup do |config| config.adapter = :json_api end
    • 啊,好吧,我认为 json_api 支持仅在 0.10 中。我建议使用它(它已经在 RC 中),否则您可以使用 JSON API page 中列出的其他库之一。 IMO,monkypatching AMS 会更痛苦:)
    【解决方案2】:

    这是怎么做的:

    class FooSerializer < ActiveModel::Serializer
      def attributes(*args)
        hash = super
        hash[:attributes] = attributes_list
        hash
      end
    
      def attributes_list
        {
          # to be filled
        }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多