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
隐式调用的参数。那我的错误在哪里?
答案 0 :(得分:7)
因为在使用json渲染时在Rails中,to_json方法将接收选项。
你可能想做这样的事情:
def to_json(options = {})
JSON.pretty_generate(self, options)
end