创建“提要"来自多个不同的 Rails 模型 [英] Creating "feeds" from multiple, different Rails models

查看:42
本文介绍了创建“提要"来自多个不同的 Rails 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个具有多种不同模型(票证、帖子、报告等)的应用程序.每个模型中的数据都不同,我想从所有这些模型中创建一个提要",以全面显示 10 个最近的条目(所有数据的混合).

I'm working on an application that has a few different models (tickets, posts, reports, etc..). The data is different in each model and I want to create a "feed" from all those models that displays the 10 most recent entries across the board (a mix of all the data).

解决这个问题的最佳方法是什么?我是否应该创建一个新的 Feed 模型并在为用户分配工单或发布新报告时写入该表?我们还一直在研究 STI 来构建模型引用表,或者只是创建一个聚合数据的类方法.不确定哪种方法最有效...

What is the best way to go about this? Should I create a new Feed model and write to that table when a user is assigned a ticket or a new report is posted? We've also been looking at STI to build a table of model references or just creating a class method that aggregates the data. Not sure which method is the most efficient...

推荐答案

您可以根据效率要求选择以下两种方式之一.

You can do it one of two ways depending on efficiency requirements.

效率较低的方法是检索 10 * N 个项目并根据需要进行排序和减少:

The less efficient method is to retrieve 10 * N items and sort and reduce as required:

# Fetch 10 most recent items from each type of object, sort by
# created_at, then pick top 10 of those.
@items = [ Ticket, Post, Report ].inject([ ]) do |a, with_class|
  a + with_class.find(:all, :limit => 10, :order => 'created_at DESC')
end.sort_by(&:created_at).reverse[0, 10]

另一种方法是创建一个索引表,该表与各种记录具有多态关联.如果您只关心一次显示 10 个,您可以使用某种 rake 任务积极修剪它,将其限制为每个用户 10 个,或者任何需要的范围.

Another method is to create an index table that's got a polymorphic association with the various records. If you're only concerned with showing 10 at a time you can aggressively prune this using some kind of rake task to limit it to 10 per user, or whatever scope is required.

这篇关于创建“提要"来自多个不同的 Rails 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆