views:

215

answers:

2

I have this block of code:

users = Array.new
users << User.find(:all, :conditions => ["email like ?", "%foo%"])
users << User.find(:all, :conditions => ["name like ?", "%bar%"])
users.flatten!
users.uniq!
puts users.to_json :include => [:licenses]

When I run it using script/console, it returns exactly what you would think it should, a JSON representation of the Array of users that I found, flattened, and uniquified. But running that same line of code as part of a search_for_users method, I get this error

TypeError in ControllerName#search_for_users
wrong argument type Hash (expected Data)

and the line referenced is the line with the .to_json call.

It's baffling me because the code is verbatim the same. The only difference is that when I'm running it in the console, I'm entering the conditions manually, but in my method, I'm pulling the query from params[:query]. But, I just tried hardcoding the queries and got the same result, so I don't think that is the problem. If I remove the :include, I don't see the error, but I also don't get the data I want.

Anyone have any idea what the issue might be?

+1  A: 

There are a few plugins and gems that can cause .to_json to fail if included in your controller. I believe that the Twitter gem is one of them (ran into a problem with this awhile back).

Do you have "include [anything]" or "require [anything]" in this controller?

If not, I'd suggest temporarily removing any plugins you're using to troubleshoot, etc.

Finally, what happens if you replace that entire controller action with simply: %w(1 2 3 4 5).to_json

That should help you pin down what is failing.

Scott Andreas
Yes! There was a `require 'json'` line at the top. Removing this fixed the issue. Thanks a lot!
jxpx777
A: 

Whenever code in tests or the console behaves different from production environment (which is a guess... you might be running your site in development mode), this calls for a load order issue. In production environment, all the models and controllers are preloaded, in other environments they are loaded lazily when needed. Start your console with RAILS_ENV=production ./script/console and see if you can reproduce the error this way. As cscotta mentioned, there are a couple of gems and librarys, that can interfere with .to_json, first to mention the functionality, that you get when you require 'json'. I personally ran into several issues with that.

Hope this helps

Seb

flitzwald