6

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?

Community
  • 1
  • 1
gorootde
  • 4,003
  • 4
  • 41
  • 83
  • and connected to this one http://stackoverflow.com/questions/9557307/rails-3-json-model-to-json-or-json-model – phoet Jul 22 '12 at 11:32

1 Answers1

10

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
Charles Barbier
  • 835
  • 6
  • 15
  • ty. Renamed the method to `as_json_response` to avoid recursion issues, and used the method body of your post. Now the controller looks as following: `render :json => response.as_json_response`. Everything works fine now. – gorootde Jul 22 '12 at 11:43