开发者

Does to_json require parameters? what about within rails?

开发者 https://www.devze.com 2022-12-30 13:04 出处:网络
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

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

开发者_StackOverflow社区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.


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 = {}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消