加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 4 – 在Rails中自定义(json)响应对象的

发布时间:2020-12-17 04:21:03 所属栏目:百科 来源:网络整理
导读:我有一个Rails控制器响应 JSON对象.让我们来看理论这个例子: respond_to :jsondef index respond_with Comment.allend 这会有类似的回应 [{"id":1,"comment_text":"Random text ","user_id":1,"created_at":"2013-07-26T15:08:01.271Z","updated_at":"2013-
我有一个Rails控制器响应 JSON对象.让我们来看理论这个例子:
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,"username": "John Doe","created_at":"3 hours ago"}]

正如你所看到的,我正在添加一个在数据库模型“username”中不存在的列,我正在取出“updated_at”,并且我将“created_at”格式化为包含人类可读文本而不是日期.

有人想过吗?

解决方法

覆盖as_json或使用JSON ERB视图可能很麻烦,这就是我更喜欢使用ActiveModel Serializers(或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

在这里查看更多信息:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读