Ruby on rails 如何使用Rails序列化程序返回对象的所有属性?

Ruby on rails 如何使用Rails序列化程序返回对象的所有属性?,ruby-on-rails,active-model-serializers,Ruby On Rails,Active Model Serializers,我有一个简单的问题。我有一个Serializer,看起来像这样: class GroupSerializer < ActiveModel::Serializer attributes :id, :name, :about, :city end def attributes object.attributes.symbolize_keys end def filter(keys) keys - [:author, :id] end 如何操

我有一个简单的问题。我有一个Serializer,看起来像这样:

class GroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :about, :city 
end
  def attributes
    object.attributes.symbolize_keys
  end
  def filter(keys)
          keys - [:author, :id]
  end

如何操作?

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

Group.new.attributes.keys
例如,我在一个应用程序上为用户获得以下信息:

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

至少在0.8.2版ActiveModelSerializer上,您可以使用以下内容:

class GroupSerializer < ActiveModel::Serializer
  def attributes
    object.attributes.symbolize_keys
  end
end
class GroupSerializer
尽管如此,请谨慎处理,因为它将添加对象附加到它的每个属性。您可能希望在序列化程序中加入一些过滤逻辑,以防止显示敏感信息(即加密密码等)

这并不涉及关联,尽管稍加挖掘,您可能会实现类似的功能

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

更新:01/12/2016


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

class GroupSerializer < ActiveModel::Serializer
  def attributes(*args)
    object.attributes.symbolize_keys
  end
end
class GroupSerializer < ActiveModel::Serializer
  def attributes(*args)
    object.attributes.symbolize_keys
  end
end
class GroupSerializer
只是为了补充@kevin的答案。我还研究了如何在返回的属性上添加过滤器。我查看了文档,它确实支持如下所示的过滤器:

class GroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :about, :city 
end
  def attributes
    object.attributes.symbolize_keys
  end
  def filter(keys)
          keys - [:author, :id]
  end
我试过了,但没用。我认为这是因为没有明确指定属性。我必须按照《工作指南》中规定的方法来做:


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

class GroupSerializer < ActiveModel::Serializer
  def attributes(*args)
    object.attributes.symbolize_keys
  end
end
class GroupSerializer < ActiveModel::Serializer
  def attributes(*args)
    object.attributes.symbolize_keys
  end
end
class GroupSerializer
我希望获得所有属性+更多属性

基于以上答案,本工作:

类NotificationSerializer
结束

你能告诉我更多吗。。问题是什么。您的意思是,您不想像这样手动放置属性名称
属性:id,:name,:about,:city
?是的,完全正确。我只希望默认情况下返回整个对象。如果需要的话,我还想排除一些东西。如何获得所有属性+更多的属性
key=object.attributes.symbolize\u keys
key[:one\u more]='haha'
像这样?@namnamam这对我来说很有用:def attributes(*\u args)object.attributes.symbolize\u keys.merge(one\u more:'haha')end