Ruby:将数组或哈希转换为活动记录关系



我正在尝试将哈希转换为活动记录关系,但无法这样做。我打算使用活动记录关系对类别表进行排序,然后过滤。最终目标是创建一个实例方法来过滤访问的前 5 个类别,然后我可以在控制器中使用/调用它们。这就是我的想法:

品类型号:

def top_5_visited
        Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5 
end

类别控制器:

@categories = Category.top_5 visited

哈希{"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112}将通过以下查询创建:

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

我还尝试使用sort_by方法将其转换为数组:

total_count_sorted = total_count.sort_by {|_key, value| value}

我已经用谷歌搜索了"将数组转换为活动记录关系"并引用了这篇文章,但对此进行了测试:

Category.where(id: total_count_sort.map(&:id))

在 Rails 控制台中,显示此错误:

NoMethodError: ["Simula", 7]:Array 的未定义方法 ID

您要执行的操作从反向结束(类别(开始,并在 ORDER 子句中使用聚合。

Category.joins(:articles)
        .order('SUM(articles.impressions_count) DESC')
        .group(:id)
        .limit(5)

irb(main):005:0> Category.joins(:articles).order("SUM(articles.impressions_count) DESC").group('categories.id').limit(5)
  Category Load (1.5ms)  SELECT  "categories".* FROM "categories" INNER JOIN "articles" ON "articles"."category_id" = "categories"."id" GROUP BY categories.id ORDER BY SUM(articles.impressions_count) DESC LIMIT $1  [["LIMIT", 5]]
=> #<ActiveRecord::Relation [#<Category id: 4, name: "C#", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 3, name: "JavaScript", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 1, name: "Simula", created_at: "2017-11-15 15:03:37", updated_at: "2017-11-15 15:03:37">, #<Category id: 2, name: "Haskell", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">]>

并且您应该创建一个类方法 - 而不是实例方法,因为这基本上只是一个范围,调用实例没有意义。

class Category < ApplicationRecord
  has_many :articles
  def self.order_by_article_impressions
    self.joins(:articles)
        .order('SUM(articles.impressions_count)')
        .group(:id)
  end
  def self.top_5_visited
    order_by_article_impressions.limit(5)
  end
  # Or use `scope` which is just syntactic sugar
  scope(:top_5_visited) -> { order_by_article_impressions.limit(5) }
end

将代码更改为:

Category.where(id: total_count_sort.map(&:last))

最新更新