【问题标题】:Simplify .to_json array result in Rails 4在 Rails 4 中简化 .to_json 数组结果
【发布时间】:2016-03-07 03:05:28
【问题描述】:

我有这个代码:

@post.to_json(include: {tags: { only: :name} } )

产生这个输出:

{ ... "tags": [{"name": "Lorem"}, {"name": "ipsum"}, {"name": "cupcake"}] ... }

当我想要的是:

{ ... "tags": ["Lorem", "ipsum", "cupcake"] ... }

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails arrays ruby json ruby-on-rails-4


    【解决方案1】:

    很简单,编写自己的序列化程序而不是尝试破解to_json

    class PostWithTagsSerializer
      attr_reader :object
    
      def initialize(object)
        @object = object
      end
    
      def as_json(*)
        hash = object.as_json
        hash[:tags] = object.tags.pluck(:name)
        hash
      end
    
      def to_json(*)
        as_json.to_json
      edn
    end
    

    然后简单地使用

    PostWithTagsSerializer.new(@post).to_json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 2011-02-04
      相关资源
      最近更新 更多