2010-01-20 18 views
10

如何合併模型以便我可以按順序顯示最後10個帖子,Feed條目和私人消息?「合併」多個模型。創建「近期活動」框

帖子都存儲在「郵報」的模型,並下令對「created_at」

飼料條目存儲在「行星」,並下令對「published_at」

悄悄話都存儲在「消息」和需要與過濾:

:conditions => "receiver_id = #{current_user.id}" 

,並下令對 「created_at」

回答

11

你必須:

  1. 查詢元素爲每個模型
  2. 在一個共同的格式將它們合併
  3. 排序和限制

下面是一些代碼:

class Activity < Struct.new(:title, :text, :date); end 

limit = 10 
activities = [] 
activities += Post.all(:order => 'created_at DESC', :limit => limit).map do |post| 
    Activity.new(post.title, post.summary, post.created_at) 
end 

activities += Planet.all(:order => 'published_at DESC', :limit => limit).map do |planet| 
    Activity.new(planet.title, planet.message, planet.published_at) 
end 

activities += Message.all(:conditions => ['receiver_id = ?', current_user.id], :order => 'created_at DESC', :limit => limit).map do |message| 
    Activity.new(message.title, message.text, message.created_at) 
end 

# descending sort by 'date' field 
sorted_activities = activities.sort_by(&:date).reverse 

# 10 most recent elements across all models 
@activities = sorted_activities[0..(limit-1)] 

當然,這取決於你的模型,你將不得不改變其方法被用作「標題」或「文本」。

但是,如果您碰巧需要很多這樣的成語,您應該像使用zena(rails CMS)那樣使用單表繼承。

+0

即時通訊有一個排序問題,它似乎聚集所有然後將所有行星組合在一起,而不是混合它們 – Arcath 2010-01-20 10:13:15

+0

使用#sort_by改爲:activities.sort_by(&:created_at).reverse [0,limit] – 2010-01-20 15:28:52

+0

謝謝,它需要是@ @ activites = activities .sort_by(&:date).reverse [0,limit]'using:date,以便它在Activity類中的字段 – Arcath 2010-01-20 15:42:30

11

我會用一個Proxy類。該類可以存儲ActiveRecord對象引用和用於排序的字段。

class ActivityProxy 
    attr_accessor :object, :date 
    def initialize(object, date) 
    self.object = object 
    self.date = date 
    end 
end 

然後你加載你的對象。

activity = [] 
activity += Post.all(:limit => 10, :order => "created_at DESC").map { |post| ActivityProxy.new(post, post.created_at) } 
# and so on with the other objects 

最後,你的對象進行排序

activity.sort_by(&:field) 
# => here you have the sorted objects 
# and you can iterate them with 
activity.each do |proxy| 
    proxy.object.id 
    # ... 
end 
+0

活動數組似乎是空的,我沒有得到任何錯誤只是在它結束時的空數組 – Arcath 2010-01-20 09:10:02

+0

更改'+'爲'+ =' – 2010-01-20 09:38:41

1

創建提要的另一種方法是創建一個VIEW,將兩者結合起來,然後讓視圖具有自己的模型。

+1

有關解釋,請參閱:https:// dan。 chak.org/enterprise-rails/chapter-11-view-backed-models/ – 2017-10-22 11:37:18