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

Precision of double lost when reading from Jackson

java json jackson

This should be a simple issue but I just couldn't find anything on the Internet.

Remove n chars from end of String

java string integer

Can I somehow remove n chars from the end of a String ?

Select Max value from sublist with LINQ

c# linq

How to write a LINQ query that would return row of type "Value" with Max Date and Max value for that date. it should be the row where name = "Correct"