我将所有信息作为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
我该怎么做?
答案 0 :(得分:1)
您可以在与methods
和include
相同的级别添加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