Rails group by id uses a string for hash key

My code looks like this:

hash = MyModel.count(:group => 'id', :conditions => 'bla = "bla"')

The returned Hash has keys that are strings. I want them to be ints. I know it would be possible to convert the Hash manually using something like a map construct.

Edit:

Thanks for the responses. Have realised it was a json conversion process that was turning the ids into Strings and rails does in fact use the Fixnum as one might expect.

Answers


When I use your code I get integer keys (rails 3.07), what's the column type of id?

If you want to do it manually:

new_hash = hash.inject({}){|h,a| h[a.first.to_i] = a.last; h}

hash = MyModel.count(group: 'id', conditions: 'bla = "bla"')

should have Fixnum keys by default since id is an instance of Fixnum.

What happens is that ActiveRecord always fetch result as strings and then Rails takes care of converting them to other datatypes according to the type of the database column (we say that they are typecast).

So it's maybe a Rails bug or the 'id' column is not set as integer(which would be surprising).

If you can't fix it, convert them manually:

hash.each_with_object({}) do |(key, value), hash|
  hash[key.to_i] = value
end

Need Your Help

Message exchange in Django how?

javascript django django-models

I am working on Django application where users can exchange post-it notes with each other. I had already found two good front-end solutions for it:

Laravel4, eager loading is not working

php laravel eloquent

I'm trying to get "reviews" from my database where the user is from MX (for example) so, I have this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.