我有2個車型類別和第三條有關這樣取COUNT(列)在與A組查詢的整數在Rails 3中
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
我訪問count_articles_per_category這樣
Article.count_articles_per_category
它將返回包含2列的文章:category_id和total。
我的問題是,總列是一個字符串。所以問題是:是否有一個方法來獲取該列作爲一個整數? PS:我試圖在數據庫中爲COUNT(*)進行強制轉換,但這並沒有幫助。 我會盡量避免做這樣的事情:
articles = Article.count_articles_per_category
articles.map do |article|
article.total = article.total.to_i
article
end
是否有可能告訴ActiveRecord計數列的類型? – panzi