【问题标题】:Rails: List items by frequency, including the frequencyRails:按频率列出项目,包括频率
【发布时间】:2019-01-10 11:21:52
【问题描述】:

以下每个类别将获得一篇文章:

Post.group(:category_id).order('count *')

然后我可以通过列出每个结果来显示代表帖子的表格,每个类别一个:

CATEGORY | SAMPLE POST ID | SAMPLE POST TITLE
        1        |             123           | How to swim out loud
        2        |             246           | On Hamlet

但是,我想包括此类别中的帖子数,例如:

CATEGORY | AMOUNT | SAMPLE POST ID | SAMPLE POST TITLE
        1        |       5       |            123           | How to swim out loud
        2        |       2       |            246           | On Hamlet

我们怎样才能显示数量,即“每组计数”?希望有一种方法可以从“发布”结果中提取它,作为相应 ActiveRecord 查询的一部分。

注意这里没有“类别”表。 category_id 只是一个独立的列。因此 counter_cache 是不可能的。

【问题讨论】:

    标签: mysql ruby-on-rails activerecord ruby-on-rails-5


    【解决方案1】:

    您可以使用一些 sql-magic(以下适用于 mysql,尚未在 postgres 中测试过,但也应该这样做):

    posts = Post.group(:category_id).order('count(*)').select('count(*) as category_cnt, posts.*')
    category_count = posts.first.category_cnt
    

    【讨论】:

    • 就是这样!非常酷,AR 支持基于查询的动态属性,谢谢?
    【解决方案2】:

    我假设你的 Post belongs_to Category

    话虽如此,rails 中有一个惊人的功能,称为counter_cache。查看文档here

    class Post < ApplicationRecord
      belongs_to :category, dependent: :destroy, counter_cache: true
    end
    
    class Category < ApplicationRecord
      has_many :posts
      # category should have a column called posts_count
    end
    

    现在,每当您创建帖子时,该类别的 posts_count 都会增加;当你删除它时,它会减少。

    对于您的列表,您可以执行以下操作:

    Category.order(posts_count: :desc) 和获取 category.posts.first

    【讨论】:

    • 曾经在 Rails 中查看过counter_cache: true 吗?
    • 其实,没有,这里没有别的表。我只是在寻找一种通用的方法来执行这种分组计数查询,没有 counter_cache 魔法(我同意如果可能的话很酷)。
    • @mahemoff 所以你有一个category_idcategory 表无关?
    • 是的,它可以是任何枚举类型,如“严重级别”。即使有另一个表,我也会很好奇如何在不记忆计数的情况下做到这一点,即直接使用查询。
    • @mahemoff 不确定这是否可以帮助您:stackoverflow.com/a/36765671/2903313 但它更像是查询和子查询表;然后您可以将结果读取为哈希
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多