Harry Wood
Harry Wood

Reputation: 2351

Does to_json require parameters? what about within rails?

Does to_json require parameters? what about within rails?

I started getting the error "wrong number of arguments (0 for 1)" when doing myhash.to_json

Unfortunately I'm not sure when this error started happening, but I guess it relates to some versions of either rails or the json gem. I suppose my code (in a rails controller) is using the ActiveSupport::JSON version of to_json, rather than the to_josn method supported by the json gem. ActiveSupport::JSON vs JSON

In environment.rb I have

RAILS_GEM_VERSION = '2.3.2'

and also

config.gem "json", :version=> '1.1.7'

It's just a simple hash structure containing primitives which I want to convert in my controller, and it was working, but now I can't seem to run to_json without passing parameters.

Upvotes: 0

Views: 894

Answers (3)

Harry Wood
Harry Wood

Reputation: 2351

to_json does not require parameters, when you're using the version provided within rails (ActiveSupport::JSON) So that error message shows that it must be trying to call the to_josn method defined in the json gem.

So my actual source of confusion was around the way rails loads these libraries.

It will load the json gem and use it within a controller, even if I don't have a line saying 'require json' because rails loads gems as defined in environment.rb, so in fact I needed to remove the line

config.gem "json", :version=> '1.1.7'

...from my environment.rb . My code had been broken since I had added that. Confusingly I do need that gem, but only for scripting I'm doing outside of rails.

Upvotes: 0

Daniel Beardsley
Daniel Beardsley

Reputation: 20367

If ActiveSupport in that version of rails has to_json, why use a gem? The Gem probably redefines Object#to_json to require arguments and thats why you are getting an error.

Look in the code of the json Gem and find where to_json is defined to verify this.

Upvotes: 0

x1a4
x1a4

Reputation: 19485

Do you have your own version of to_json defined in a model that doesn't take args? If so, make it accept *args or opts = {}

Upvotes: 0

Related Questions