0

我有可以按类别标记的文章。我正在努力创建一个查询,该查询将提取每个类别中文章的查看次数总和(使用印象派 gem 跟踪)。

架构:

  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

文章类别模型

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
4

1 回答 1

1

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

Article.joins(:categories).group('categories.name').sum(:impressions_count)
于 2017-11-15T10:35:20.113 回答