创建“提要”来自多个不同的 Rails 模型
我正在开发一个具有几种不同模型(票证、帖子、报告等)的应用程序。每个模型中的数据都不同,我想从所有这些模型中创建一个“提要”,全面显示 10 个最新条目(所有数据的混合)。
解决这个问题的最佳方法是什么?当为用户分配票证或发布新报告时,我是否应该创建一个新的 Feed 模型并写入该表?我们还一直在研究 STI 来构建模型引用表或只是创建聚合数据的类方法。不确定哪种方法最有效...
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).
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以根据效率要求选择两种方法之一。
效率较低的方法是检索 10 * N 项并根据需要进行排序和缩减:
另一种方法是创建一个与各种记录具有多态关联的索引表。如果您只关心一次显示 10 个,您可以使用某种 rake 任务积极修剪它,将其限制为每个用户 10 个,或任何需要的范围。
You can do it one of two ways depending on efficiency requirements.
The less efficient method is to retrieve 10 * N items and sort and reduce as required:
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.
创建一个包含属性“table_name”和“item_id”的项目模型。然后为每种数据类型创建一个部分。保存后,假设保存了一张票证,创建一个 Item 实例:
在 items_controller 中:
在 views/items/index.erb 中:
Create an Item model that includes the attributes "table_name" and "item_id". Then create a partial for each data type. After you save, let's say, a ticket, create an Item instance:
In your items_controller:
In views/items/index.erb: