Creating “feeds” from multiple, different Rails models

我们两清 提交于 2019-11-30 05:18:09

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:

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

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.

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:

i = Item.create(:table_name => 'tickets', :item_id => @ticket.id)

In your items_controller:

def index
   @items = Item.find(:all, :order => 'created_on DESC')
end

In views/items/index.erb:

<% @items.each do |item| %>
  <%= render :partial => item.table_name, :locals => {:item => item} %><br />
<% end %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!