ActiveModel :: Serializer定义属性属性?

时间:2016-01-07 14:22:03

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

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

class FooSerializer < ActiveModel::Serializer
  attributes :attributes

  def attributes
    {
      # to be filled
    }
  end
end

将覆盖原始方法。是否有可能以某种方式添加属性字段?

2 个答案:

答案 0 :(得分:2)

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

ActiveModelSerializers.config.adapter = :json_api

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

答案 1 :(得分:0)

方法如下:

class FooSerializer < ActiveModel::Serializer
  def attributes(*args)
    hash = super
    hash[:attributes] = attributes_list
    hash
  end

  def attributes_list
    {
      # to be filled
    }
  end
end
相关问题