Rails "wrong number of arguments (1 for 0)" in to_json method [duplicate]
Asked Answered
T

1

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?

Telescopium answered 22/7, 2012 at 10:46 Comment(1)
and connected to this one #9557807Ouidaouija
C
11

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
Caxton answered 22/7, 2012 at 11:35 Comment(1)
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.Telescopium

© 2022 - 2024 — McMap. All rights reserved.