Rails ActiveRecord查询:每个类别的总文章视图计数

时间:2017-11-15 10:01:18

标签: ruby-on-rails ruby activerecord impressionist

我有能够按类别标记的文章。我正在努力创建一个查询,它将提取每个类别中文章的视图数量(使用印象派宝石跟踪)的总和。

架构:

  create_table "article_categories", force: :cascade do |t|
    t.integer "article_id"
    t.integer "category_id"
  end

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "impressions_count", default: 0
  end

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

文章模型

class Article < ApplicationRecord
  is_impressionable :counter_cache => true, :unique => false
  belongs_to :user
  has_many :impressions, as: :impressionable
  has_many :article_categories
  has_many :categories, through: :article_categories
end

类别模型

class Category < ApplicationRecord
  has_many :article_categories
  has_many :articles, through: :article_categories
end

ArticleCategory模型

class ArticleCategory < ActiveRecord::Base
  belongs_to :article
  belongs_to :category
end

这是我到目前为止所尝试的以及在rails控制台中测试时的错误:

cat_group = Article.joins(:article_categories).group_by(&:category_ids)
// this query results in an array of articles within each category

1) cat_group.sum("impressions_count")
//TypeError: no implicit conversion of Array into String

2) cat_group.select("sum(impressions_count) AS total_count")
//ArgumentError: wrong number of arguments (given 1, expected 0)

3) Article.joins(:article_categories).group(:category_id)

//ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "articles.id" must appear in the GROUP BY clause or be used in an aggregate function

1 个答案:

答案 0 :(得分:1)

如果我理解正确且查看次数impressions_count,则可以使用以下查询:

Article.joins(:categories).group('categories.name').sum(:impressions_count)