2012-06-03 2 views
2

Category 모델의 경우 category에 일부 하위 범주 (category.categories)가있을 수 있습니다. 나는 Category에 서브가없는 모든 것을 제공하는 범위를 원한다. categories.연관 없음에 대한 레일 범위 검사

, 나는

without_subcategories = Category.select{|category| category.categories.none?} 

을 쓸 수 있지만, 나는 scope으로 이것을 쓰고 싶습니다. 어떻게해야합니까?

class Category < ActiveRecord::Base 
    belongs_to :parent, class_name: 'Category' 
    has_many :categories, foreign_key: :parent_id, class_name: 'Category' 
    scope :without_subcategories, lambda { WHAT GOES IN HERE? } 
end 
+0

레일스 3.2, activerecord 및 postgresql을 사용하고 있습니다. – Peter

답변

4

가장 좋은 방법은 카운터 캐시를 구현하여 DB 쿼리를 최소화 할 수 있습니다 : 경우

그것이 명확하지, 이건 내 모델입니다. 레일에서는 belongs_to 연관에 :counter_cache => true 옵션을 추가하여 매우 간단합니다. 여기서는 카테고리 db 테이블에 'categories_count' 정수 컬럼을 작성한다고 가정합니다. 이 점을 감안할 때, 귀하의 범위는 사소한 것입니다.

class Category < ActiveRecord::Base 
    belongs_to :parent, class_name: 'Category', :counter_cache => true 
    has_many :categories, foreign_key: :parent_id, class_name: 'Category' 
    scope :without_subcategories, where(categories_count: 0) 
end 

희망이 도움이되었습니다.

+1

이 경우에는'lambda'가 필요 없습니다. 단지'scope : without_subcategories, where (: categories_count => 0)'이면 충분합니다. –

+0

ta mu, 업데이트 된 답변 –

+0

@viktortron : 동료 키위? :) – Peter