Ruby on rails Rails to_json静态方法:TypeError X不是符号

Ruby on rails Rails to_json静态方法:TypeError X不是符号,ruby-on-rails,json,serialization,static,Ruby On Rails,Json,Serialization,Static,我希望我的to_json包含来自控制器的静态方法 class ApplicationController < ActionController::Base def self.server_time Time.now end end 及 但是我得到了类型错误: TypeError: 2013-04-04 08:33:31 +0300 is not a symbol o是一个ActiveRecord对象 适用于我,但你也可以: [o, ApplicationCont

我希望我的to_json包含来自控制器的静态方法

class ApplicationController < ActionController::Base   
  def self.server_time
    Time.now
  end 
end

但是我得到了类型错误

TypeError: 2013-04-04 08:33:31 +0300 is not a symbol
o是一个ActiveRecord对象


适用于我,但你也可以:

[o, ApplicationController.server_time].to_json


要在json中包含时间,如果您希望json像以前一样具有新键“time”,请执行以下操作:

还可以使用时间键和对象键:

{time: ApplicationController.server_time, object: o}.to_json
 # => {time:123, object: {id:1, name: 'name', ...} }
由于Rails的魔力,您不必在控制器中指定
to_json

render json: o.as_json.merge({time:ApplicationController.server_time})
# or the other option
render json: {time: ApplicationController.server_time, object: o}

抱歉,您想包含方法代码或方法结果吗?@ted抱歉,不清楚。方法结果,你所说的方法代码是什么意思?
Time。现在
serialized(:xdsemx给出的答案也适用于我。你的示例中有一个带有当前时间的json和
o
[o, ApplicationController.server_time].to_json
{ApplicationController.server_time: o}.to_json
o.as_json.merge({time:ApplicationController.server_time}).to_json
# => {time:123, id:1, name: 'name', ...}
{time: ApplicationController.server_time, object: o}.to_json
 # => {time:123, object: {id:1, name: 'name', ...} }
render json: o.as_json.merge({time:ApplicationController.server_time})
# or the other option
render json: {time: ApplicationController.server_time, object: o}