创建“提要"从多个导轨模型有效地进行? [英] Creating a "feed" from multiple rails models, efficiently?

查看:52
本文介绍了创建“提要"从多个导轨模型有效地进行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对>"feeds"来自多个不同的Rails模型.在这个问题中,tadman建议使用这种方法从三种模型(票证,帖子,报告)中创建最近项目的用户供稿:

This is a follow up to Creating "feeds" from multiple, different Rails models. In this question, tadman suggests this method of creating a user feed of recent items from three models (Ticket, Post, Report):

 @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]

他建议这是一种可行的方法,但不一定是最有效的方法.他建议,还有一种替代方法是创建一个索引表,该索引表与各种记录具有多态关联."

He suggests this as a method that will work, but that won't necessarily be the most efficient. He suggests as well than an alternative method would be to "create an index table that's got a polymorphic association with the various records."

我真的很想了解更多有关此替代解决方案的信息,它看起来既高效又优雅.谁能告诉我该怎么做?让我们使用上一个问题中的相同背景信息作为基础.

I'm really interested in learning more about this alternative solution, it seems both more efficient and more elegant. Can anyone tell me how one would do this? Let's use the same background info from the last question as a base.

推荐答案

我曾经做的是,有一个单独的模型Feed(feeds_controller),并在after_save回调中将其更新为所有interesting模型.因此,例如,如果您有模型文章,则可以使用after_save回调:

What I did once was, have a separate model Feed (feeds_controller) and update it in after_save callbacks to all the interesting models. So for example if you have a model Article, have an after_save callback:

def after_save
  feed = Feed.new
  feed[:model_name] = 'Article'
  feed[:item_id] = id
  feed.save
end

然后,您可以像访问其他模型一样线性访问提要.保存提要而不是从提要中读取时会产生计算费用.

then, you can access the feed linearly just like any other model. The computational expense is incurred when saving the the feed, not reading from the feed.

哦,您还可以使用Feed has_many :article; has_many :user, has_many :status等,然后在feed中使用:include所有这些资源,并将其呈现在视图中.希望这是有道理的;-)

Oh, you can also have Feed has_many :article; has_many :user, has_many :status and so forth, and then :include all those resources in the feed, and render them in views. Hope this makes sense ;-)

这篇关于创建“提要"从多个导轨模型有效地进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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