【问题标题】:How do I use active_model_serializers to include by default all attributes and filter them?如何使用 active_model_serializers 默认包含所有属性并过滤它们?
【发布时间】:2013-03-09 01:00:01
【问题描述】:

我正在使用active_model_serializers 并且想找到一种方法来默认包含所有模型的属性,然后使用类似的东西

       exclude :date_created, :first_name

指定我不需要的那些。

到目前为止,除了文档中的属性之外,我还没有找到一种方法来指定导出的属性,这是通过枚举所有需要的属性来完成的:

       attributes :title, :body

【问题讨论】:

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


    【解决方案1】:

    你可以在你的模型序列化器上做这样的事情(以 User 作为模型):

    class UserSerializer < ApplicationModelSerializer
       attributes(*User.attribute_names.map(&:to_sym))
    end
    

    有关 ActiveRecord 属性名称的更多信息可以在这里找到:http://apidock.com/rails/ActiveRecord/AttributeMethods/attribute_names

    【讨论】:

    • 谢谢。最终的解决方案是:attributes(*(User.attribute_names - ["date_created", "first_name"] ).map(&amp;:to_sym))
    • 我收到了一个错误,请在这里参考我的答案:stackoverflow.com/a/27701138/243797
    • 不幸的是attributes 不接受数组作为输入:(
    • @Tilo:这就是为什么他们在数组前面使用星号 (*)。它将数组转换为参数列表。
    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    相关资源
    最近更新 更多