【问题标题】:Rails "wrong number of arguments (1 for 0)" in to_json method [duplicate]在to_json方法中Rails“参数数量错误(1代表0)”[重复]
【发布时间】:2012-07-20 22:13:39
【问题描述】:

可能重复:
Override to_json in Rails 2.3.5

lib/responses.rb

module Responses
class Response
    def to_json
       JSON.pretty_generate(self)
    end
end

class ErrorResponse < Response
    def initialize(cause)
        self[:type]="Error"
        self[:casue]=cause

    end
end
class DataResponse < Response
    attr_accessor :data

end
end

这是由控制器使用的:

 response=Responses::DataResponse.new
 response.data=someData

 render :json => response

现在我在lib/responses.rb:3:in to_json 中收到错误wrong number of arguments (1 for 0)。 为什么?没有参数传递给to_json,它被render :json 隐式调用。那么我的错误在哪里?

【问题讨论】:

标签: ruby-on-rails ruby json


【解决方案1】:

这是因为在Rails中当你用json渲染时,to_json方法会接收选项。

你可能想做这样的事情:

def to_json(options = {})
   JSON.pretty_generate(self, options)
end

【讨论】:

  • 泰。将方法重命名为as_json_response 以避免递归问题,并使用您帖子的方法主体。现在控制器如下所示:render :json =&gt; response.as_json_response。现在一切正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多