【问题标题】:Rails 4 - Customizing (json) format of response objects in RailsRails 4 - 在 Rails 中自定义响应对象的 (json) 格式
【发布时间】:2013-07-26 16:41:57
【问题描述】:

我有一个使用 JSON 对象响应的 Rails 控制器。让我们以这个理论例子为例:

respond_to :json
def index 
  respond_with Comment.all
end

这会以类似

的方式响应
[{"id":1,"comment_text":"Random text ", "user_id":1  ,"created_at":"2013-07-26T15:08:01.271Z","updated_at":"2013-07-26T15:08:01.271Z"}]

我正在寻找的是一种“最佳实践”方法来干扰 json 对象的格式并返回如下内容:

[{"id":1,"comment_text":"Random text ", "username": "John Doe", "user_id":1  ,"created_at":"3 hours ago"}]

如您所见,我正在添加数据库模型“username”中不存在的列,我正在取出“updated_at”,并且正在格式化“created_at”以包含人类可读的文本而不是比约会。

有什么想法吗?

【问题讨论】:

标签: ruby-on-rails json


【解决方案1】:

覆盖 as_json 或使用 JSON ERB 视图可能很麻烦,这就是我更喜欢使用 ActiveModel 序列化器(或 RABL)的原因:

class CommentSerializer < ActiveModel::Serializer
  include ActionView::Helpers::DateHelper

  attributes :id, :created_at

  def created_at
    time_ago_in_words(object.created_at)
  end

end

查看这里了解更多信息:

  1. https://github.com/rails-api/active_model_serializers
  2. https://github.com/nesquena/rabl

【讨论】:

    【解决方案2】:

    两种方式:

    首先:定义一个视图,在其中构建并返回一个哈希值,然后将其转换为 json。

    控制器:

    YourController < ApplicationController
      respond_to :json
    
      def index
        @comments = Comment.all
      end
    end
    

    查看:index.json.erb

    res = {
      :comments => @comments.map do |x|
        item_attrs = x.attributes
        item_attrs["username"] = calculate_username
      end
    }
    
    res.to_json.html_safe
    

    第二个:使用 gem active_model_serializers

    【讨论】:

      【解决方案3】:

      我会重新定义您模型的 as_json 方法。

      在您的评论模型中,

      def username
        "John Doe"
      end
      
      def time_ago
        "3 hours ago"
      end
      
      def as_json(options={})
        super(:methods => [:username, :time_ago], except: [:created_at, :updated_at])
      end
      

      您不必更改控制器

      查看as_json的文档

      【讨论】:

      • 使用to_json方法,传递你想要的选项,简单灵活。您可以轻松地使用不同的操作从模型中传递更多或更少的属性。所有细节都在上面链接的文档中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2018-12-25
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多