Rails“参数数量错误(1代表0)"在to_json方法中 [英] Rails "wrong number of arguments (1 for 0)" in to_json method
本文介绍了Rails“参数数量错误(1代表0)"在to_json方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在Rails 2.3.5中覆盖to_json
Possible Duplicate:
Override to_json in Rails 2.3.5
lib/responses.rb
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
隐式调用.那我的错误在哪里?
Now I am getting an error wrong number of arguments (1 for 0)
in lib/responses.rb:3:in to_json
.
Why? There is no argument passed to the to_json
which is implicitly called by render :json
. So where is my mistake?
推荐答案
这是因为在Rails中使用json渲染时,to_json方法将接收选项.
Its because in Rails when you render with json, the method to_json will receive options.
您可能想要执行以下操作:
You probably want to do something like this:
def to_json(options = {})
JSON.pretty_generate(self, options)
end
这篇关于Rails“参数数量错误(1代表0)"在to_json方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文