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)
이 코드는 테스트되지 않은 상태에서 데이터를 가져 오는, 그러나 아이디어를 제공합니다.
선호하는 부울을 갖고 있습니까? 아니면 자동으로 평가하는 곳에서 더 복잡한 부울을 원하십니까? 자세한 정보를 제공하십시오. –
아니요, 선호하는 부울 없음 게시물의 범주/작성자와 해당 특정 사용자의 "즐겨 찾기"카테고리/작성자를 기준으로 선호하는 모델을 결정하려면 즐겨 찾기 모델을 사용해야합니다. – imderek