Fetch COUNT(column) as an integer in a query with group by in Rails 3

I have 2 models Category and Article related like this:

class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category

  def self.count_articles_per_category
    select('category_id, COUNT(*) AS total').group(:category_id)
  end
end

I'm accessing count_articles_per_category like this

Article.count_articles_per_category

which will return articles that have 2 columns: category_id and total.

My problem is that total column is a string. So the question is: is there a method to fetch that column as an integer?

PS: I tried to do a cast in the database for COUNT(*) and that doesn't help. I try to avoid doing something like this:

articles = Article.count_articles_per_category
articles.map do |article|
  article.total = article.total.to_i
  article
end 

Answers


No, there is no support in ActiveRecord to automatically cast datatypes (which are always transferred as strings to the database).

The way ActiveRecord works when retrieving items is:

  • for each attribute in the ActiveRecord model, check the column type, and cast the data to that type.
  • for extra columns, it does not know what data type it should cast it to.

Extra columns includes columns from other tables, or expressions.


You can use a different query, like:

Article.group(:category_id).count
Article.count(:group => :category_id)

These return a hash of :category_id => count. So you might get something like {6=>2, 4=>2, 5=>1, 2=>1, 9=>1, 1=>1, 3=>1}.

Using the count method works because it implicitly lets ActiveRecord know that it is an integer type.


Article.group(:category_id).count might give you something you can use. This will return a hash where each key represents the category_id and each value represents the corresponding count as an integer.


Need Your Help

how to managing hibernate session in spring

java spring hibernate tomcat hibernate-session

i have problem with session close what impact during running this application and what if this goes in production.

accessing value of input field by id using jquery

javascript jquery

suppose name of an id is store in a variable x (var x="big";), i was hoping to access the value of an input field whose id is big

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.