2011-06-01 34 views
1

我需要在Rails中創建和分頁列表的幫助。我有三類:Rails中的分頁和操作列表3

class User < ActiveRecord::Base 
    has_many :rankings, :dependent => :destroy 
    #... 
    # has id, name, email, etc. 
end 

class Ranking < ActiveRecord::Base 
    belongs_to :essay 
    belongs_to :user 
    #... 
    #has comment, score, essay_id, user_id 
end 

class Essay < ActiveRecord::Base 
    has_many :rankings, :dependent => :destroy 
    #... 
    #has id, body, author, etc. 
end 

的等級類被創建爲每篇文章的評論,然後再獲取其essay_iduser_id相應的設置,所以我們知道誰排它的文章。

現在在應用程序的主頁上,我想顯示用戶尚未排名的所有論文的分頁列表。我希望列表current_user還沒有傾斜所有的散文。對於我所有的文章,我都很簡單的做@essays = Essay.paginate(:page => params[:page]),但我想要一個特定的子集。我是否需要創建一系列未排序的散文?

回答

0

這是一個建議,不使用連接。

首先獲得用戶已躋身

essay_ids = User.first.essay_ids 

然後讓所有的文章不包含這些ID的文章的所有ID)

@essays = Essay.where('id NOT IN (?)', essay_ids + [0]) 

我喜歡添加額外的0,使得空數組不會搞砸查詢。

你可以在作文中範圍廠這

scope :not_ranked_by_user, lambda {|user| where('id NOT IN (?)', user.essay_ids + [0]) } 
+0

不導軌使.essay_ids方法,如果我有一個.essay_id屬性?並且用戶沒有essay_id,所以我無法獲得essay_ids列表。那會返回一個數組嗎?我確定我可以弄清楚如何獲取數組中的所有內容,但分頁並不真正適用於數組。我如何分頁:not_ranked_by_user?對不起......很多問題 – Rymo4 2011-06-02 06:58:08