Possible Duplicate:
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
This is used by the controller:
response=Responses::DataResponse.new
response.data=someData
render :json => response
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With