2011-08-04 73 views
0

我有一個屬於單個類別和作者的Post模型。用戶可以爲類別和作者創建「最愛」。我怎樣才能最有效地查詢所有帖子的列表,但訪客的首選類別和/或作者排在頂部?Rails:優先/排序記錄集合

class Post < ActiveRecord::Base 

    belongs_to :category 
    belongs_to :author 

end 

class Favorite < ActiveRecord::Base 

    belongs_to :user 
    belongs_to :category # favorite category 
    belongs_to :author # favorite author 

end 

class User < ActiveRecord::Base 

    has_many :favorites 

end 
+0

你有一個首選布爾值還是你想它更復雜的地方,它會自動評估他們?請提供更多信息。 –

+0

不,沒有首選的布爾值。它需要使用收藏夾模型根據帖子的類別/作者以及該特定用戶的「收藏」類別/作者來確定哪些帖子是首選。 – imderek

回答

0
class User < ActiveRecord::Base 
    has_many :favorites 

    has_many :favorite_categories, :through => :favorites, :source => :category 
    has_many :favorite_authors, :through => :favorites, :source => :author 
end 

class Favorite < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :category # favorite category 
    belongs_to :author # favorite author 
end 

class Post < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :author 

    named_scope :order_by_user, lambda {|user| where(
    :category_id => user.favorite_categories.map(&:id), 
    :author_id => user.favorite_authors.map(&:id) 
)} 
end 

user = User.first 
posts = Post.order_by_user(user) 

候補:查詢的數目較少,但用戶模型從Favorite

class Favorite < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :category # favorite category 
    belongs_to :author # favorite author 
end 

class User < ActiveRecord::Base 
    has_many :favorites 

    def favorite_category_ids 
    Favorite.where(:user_id => self.id).select(:category_id).map(&:category_id).compact 
    end 

    def favorite_author_ids 
    Favorite.where(:user_id => self.id).select(:author_id).map(&:author_id).compact 
    end 
end 

class Post < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :author 

    named_scope :order_by_user, lambda {|user| where(
    :category_id => user.favorite_category_ids, 
    :author_id => user.favorite_author_ids 
)} 
end 

user = User.first 
posts = Post.order_by_user(user) 

此代碼未測試獲取數據,但給出了主意。

+0

輝煌。謝謝。 – imderek