在to_json方法中使用Rails“错误的参数数量(1为0)”

可能重复:
在Rails 2.3.5中覆盖to_json

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隐式调用。 那我的错误在哪里?

因为在使用json渲染时在Rails中,方法to_json将接收选项。

你可能想做这样的事情:

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