2011-08-04 7 views
0

단일 카테고리와 작성자에 속하는 게시물 모델이 있습니다. 사용자는 카테고리 및 저자에 대해 "즐겨 찾기"를 만들 수 있습니다. 모든 게시물의 목록을 가장 효율적으로 쿼리 할 수 ​​있지만 방문자의 기본 카테고리 및/또는 작성자가 맨 위에 정렬되어 있습니까?레일 : 레코드 컬렉션의 우선 순위 지정/정렬

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

Brilliant. 고맙습니다. – imderek