返回方法中的时间差为JSON

时间:2016-01-29 18:10:16

标签: ruby-on-rails ruby json

我将所有信息作为JSON返回。

我想在很久以前创建它。

include ActionView::Helpers::DateHelper

def as_json(options={})
  super(:only => [:id, :yell_type, :status, :payment_type],
        :include => {
            :trade_offer => {:only => [:id, :title, :description, :price],
                             :include => [:photos => {:only => [:id, :url]}]
            },
            :categories => {:only => [:id, :name]},
            :user => {:only => [:id, :name, :avatar]}
        },
        :methods => [ times_ago(:create_at) ]
  )
end

def times_ago(create_at)
  time_ago_in_words(create_at)
end

这会返回错误:

comparison of Symbol with Time failed

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在与methodsinclude相同的级别添加only。所以方法的返回值也将在JSON中传递。在这种情况下,您应该在模型中实现一个返回所需内容的方法times_ago

def as_json(options={})
  super(
    :only => [:id, :yell_type, :status, :payment_type],
    :include => {
        :trade_offer => {:only => [:id, :title, :description, :price],
                         :include => [:photos => {:only => [:id, :url]}]
        },
        :categories => {:only => [:id, :name]},
        :user => {:only => [:id, :name, :avatar]}
    },
    :methods: [ :times_ago ]
  )
end