繁体   English   中英

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

[英]Rails “wrong number of arguments (1 for 0)” in to_json method [duplicate]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM