gor*_*tde 4 ruby json ruby-on-rails
可能重复:
在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
Run Code Online (Sandbox Code Playgroud)
这由控制器使用:
response=Responses::DataResponse.new
response.data=someData
render :json => response
Run Code Online (Sandbox Code Playgroud)
现在,我得到一个错误wrong number of arguments (1 for 0)在lib/responses.rb:3:in to_json.为什么?没有参数传递给to_json隐式调用的render :json.那我的错误在哪里?
因为在使用json渲染时在Rails中,方法to_json将接收选项.
你可能想做这样的事情:
def to_json(options = {})
JSON.pretty_generate(self, options)
end
Run Code Online (Sandbox Code Playgroud)