2015-01-15 2 views
0

에 조건이의 내가 있다고 가정 해 봅시다 Item 모델과 has_many :through 협회와 Category 모델 :레일 - 열망로드 has_many : 통해 연결

class Item < ActiveRecord::Base 
    has_many :category_items 
    has_many :categories, through: category_items 
end 

class Category < ActiveRecord::Base 
    has_many :category_items 
    has_many :items, through: category_items 
end 

class CategoryItems < ActiveRecord::Base 
    belongs_to :category 
    belongs_to :items 
end 

지금, 나는 모든 항목을 얻을 것이다 항목에 대한 범위를 갖고 싶어 특정 카테고리에 대한 특정 상태 (상태 속성이 있다고 가정). 카테고리가 "재고 있음"이고 id = 3 인 카테고리에 속한 모든 항목을 가져 오십시오. scope :in_stock_for_category, ->(category) { where(status: SOME_ENUMERATED_VALUE) .... 결과 집합을 특정 카테고리로 제한하기 위해 검색어의 마지막 부분이 누락되었습니다.

감사합니다. 당신이 당신의 items 테이블에 category_id 열이 없기 때문에

답변

1

, 당신은 당신이 특정 카테고리의 ID 조건을 지정할 수 있습니다 전에 범위에 category_items 또는 cateogeries 중 하나에 가입해야합니다.

class Item < ActiveRecord::Base 
    scope :in_stock_for_category, -> do |category| 
    joins(:category_items). 
    where(category_items: {category_id: category.id}). 
    where(items: {status: SOME_ENUMERATED_VALUE}). 
    group("items.id") # grouping might be unnecessary since you're adding the where condition for the category's id 
    end 
end 

이렇게하면됩니다. 당신이 categories에 가입하려는 경우 또는, 다음을 수행하십시오

class Item < ActiveRecord::Base 
    scope :in_stock_for_category, -> do |category| 
    joins(:categories). 
    where(categories: {id: category.id}). 
    where(items: {status: SOME_ENUMERATED_VALUE}). 
    group("items.id") # grouping might be unnecessary since you're adding the where condition for the category's id 
    end 
end 

이미 그러나 category이있는 경우, 특정 상태를 가지고있는 항목에 대한 has_many 관계를 만드는 데 유용 할 수 있습니다. 다음과 같은 뭔가 : 당신이 (scope :in_stock, -> { where(status: SOME_ENUMERATED_VALUE) } 같은) Item의 상태 범위가있는 경우

class Category < ActiveRecord::Base 
    has_many :in_stock_items, -> do 
    where(items: {status: SOME_ENUMERATED_VALUE}) 
    end, through: :category_items, source: :item 
end 

또한, 당신은 대부분 다음 위의 has_many 관계 변경할 수 있습니다

class Category < ActiveRecord::Base 
    has_many :in_stock_items, -> do 
    merge(Item.in_stock) # http://apidock.com/rails/ActiveRecord/SpawnMethods/merge 
    end, through: :category_items, source: :item 
end 

을 그해야 깔끔한 것들.

+0

감사합니다. 좋은 대답. –

+0

BTW - 여기에 필요한'group ("items.id")'입니까? 그것의 목적은 무엇입니까? –

+0

'join '후에, 항목이 많은 카테고리를 가질 수 있기 때문에 동일한 항목을 가진 여러 행이있을 수 있습니다. 'items.id'로 결과를 그룹화하면 행당 하나의 항목을 얻게됩니다. – Humza

관련 문제