2011-08-04 5 views
0

私は1つのカテゴリと著者に属する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

関連する問題