如何使用多个类别的总和来优化 ActiveRecord 查询
模型:
- 用户 has_many 类别、has_many 条目
- 类别 has_many 条目
- 属于类别和用户
让我们假设,条目上有名称和金额。 如果我有一个视图需要为特定用户显示特定月份(现在让我们使用created_at),并且想要显示一个表,其中包含该特定月份中按类别分组的所有条目(不显示空类别)和总和以及类别内的条目数。
我的问题是: 查询数据库(并充分利用缓存)最有效的方法是什么?该视图将经常呈现,并且每次用户创建新条目时,一个类别的总和自然会发生变化,但其他类别的总和不会发生变化。
Models:
- User has_many Categories, has_many Entries
- Category has_many Entries
- Entry belongs_to both Category and User
Let's assume, there is a name and an amount on entries.
If I have a view that needs to display a particular month (let's take created_at for now) for a specific user and want to display a table with all entries in that particular month grouped by categories (empty categories are not displayed) and with a sum and count of the entries within a category.
My question is:
What is the most efficient way to query the database (and make best use of caching)? This view will be rendered quite often and each time a new entry is created by the user, naturally the sum of one category changes but not those of the others.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查询部分可以通过范围非常简单地完成:
然后可以循环:
当然,缓存这要求您在本月创建条目时刷新缓存。例如,您可以像这样缓存查询:
然后,当使用 user_id 和条目创建的月份创建新条目时,只需将其过期即可。我想说,在尝试单独缓存每个类别的条目之前,您应该首先使用这种方法。该查询应该执行得相当快,因此您不必深入研究单独缓存每一行。它还将执行单个查询,而不是针对每个类别执行一个查询。
这就是为什么我不会单独缓存每一行:
The query part can be accomplished quite simply with a scope:
Which can then be looped over:
Of course, caching this requires that you refresh the cache anytime an entry is created this month. For example, you could cache the query like this:
And then simply expire it when a new entry is created by using the user_id and the entry created_at month. I would say that you should use this approach first, before trying to cache every single category's entries individually. This query should perform quite quickly, so you shouldn't have to delve into caching each row individually. It will also perform a single query rather than one for each category.
Here is why I wouldn't cache each row individually:
潘老师的回答很完美,很有帮助。对于档案:这是我在应用程序中使用的查询:
Pan's answer was perfect and of great help. For the archives: this is the query I used in my app: