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
No, there is no support in
ActiveRecordto automatically cast datatypes (which are always transferred as strings to the database).The way
ActiveRecordworks when retrieving items is:ActiveRecordmodel, check the column type, and cast the data to that type.Extra columns includes columns from other tables, or expressions.
You can use a different query, like:
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
countmethod works because it implicitly lets ActiveRecord know that it is an integer type.