在to_json方法中Rails“错误的参数数量(1表示0)”

时间:2012-07-22 10:46:21

标签: ruby-on-rails ruby json

  

可能重复:
  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

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

1 个答案:

答案 0 :(得分:7)

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

你可能想做这样的事情:

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