如何使用Rails Serializer返回对象的所有属性?

时间:2015-03-27 11:02:45

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

我有一个简单的问题。我有一个看起来像这样的序列化器:

class GroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :about, :city 
end

问题在于,每当我更改模型时,我都必须在此序列化程序中添加/删除属性。我只想默认获取整个对象,就像默认的rails json response:

一样
render json: @group

我该怎么做?

4 个答案:

答案 0 :(得分:14)

至少在0.8.2的ActiveModelSerializers上,您可以使用以下内容:

class GroupSerializer < ActiveModel::Serializer
  def attributes
    object.attributes.symbolize_keys
  end
end

请注意这一点,因为它会添加您的对象附加到其上的每个属性。您可能希望在序列化程序中加入一些过滤逻辑,以防止显示敏感信息(即加密密码等)。

这并不涉及协会,虽然稍微挖掘一下你可能会实现类似的东西。

=============================================== =============

更新时间:01/12/2016

在0.10.x版本的ActiveModelSerializers上,属性默认接收两个参数。我添加了 * args 以避免异常:

class GroupSerializer < ActiveModel::Serializer
  def attributes(*args)
    object.attributes.symbolize_keys
  end
end

答案 1 :(得分:1)

只是为了添加@kevin的答案。我还想了解如何在返回的属性上添加过滤器。我查看了文档active_model_serializers 0.9,它确实支持看起来像这样的过滤器:

  def attributes
    object.attributes.symbolize_keys
  end
  def filter(keys)
          keys - [:author, :id]
  end

我试了一下,但没办法。我认为这是因为没有明确指定属性。我必须按照rails cast中指定的相同方式执行此操作:

@@except=[:author, :id]
def attributes
    data = object.attributes.symbolize_keys
    @@except.each { |e| data.delete e  }
    data
end

答案 2 :(得分:0)

尝试以下操作以获取Group类的所有属性键:

Group.new.attributes.keys

例如,我在一个应用上为用户提供以下内容:

> User.new.attributes.keys
=> ["id", "password_digest", "auth_token", "password_reset_token", "password_reset_requested_at", "created_at", "updated_at"]

答案 3 :(得分:0)

在0.10.x版本的ActiveModelSerializers上,属性默认接收两个参数。我添加了 * args 以避免异常:

class GroupSerializer < ActiveModel::Serializer
  def attributes(*args)
    object.attributes.symbolize_keys
  end
end