【问题标题】:How to return all attributes of an object with Rails Serializer?如何使用 Rails 序列化器返回对象的所有属性?
【发布时间】:2015-03-27 11:02:45
【问题描述】:

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

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

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

render json: @group

我该怎么做?

【问题讨论】:

  • 你能告诉更多..有什么问题。您的意思是,您不想像attributes :id, :name, :about, :city 这样手动 输入属性名称?
  • 是的,完全正确。我只希望整个对象默认返回。如果需要,我还想排除一些东西。

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


【解决方案1】:

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

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

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

这并没有解决关联问题,尽管稍微深入研究一下你可能会实现类似的东西。

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

更新:2016 年 1 月 12 日

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

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

【讨论】:

  • 如何获得所有属性+更多属性? key = object.attributes.symbolize_keyskey[:one_more] = 'haha'这样吗?
  • @NamNamNam 这对我有用:def attributes(*_args) object.attributes.symbolize_keys.merge(one_more: 'haha') end
【解决方案2】:

只是为了添加到@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

【讨论】:

    【解决方案3】:

    尝试以下方法获取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"]
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        我想要获得所有属性 + 更多属性。

        根据上面的答案,这项工作:

        class NotificationSerializer < ActiveModel::Serializer
        
        def actor
          'asdasd'
        end
        
        def attributes(*args)
          keys = object.attributes
          keys[:actor] = actor()  # add attribute here
          keys.symbolize_keys
        end
        

        结束

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多