2011-08-04 48 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