0

2つのモデルがあります。has_and_belongs_to_manyに関連付けられているレシピとカテゴリがあります。カテゴリ別にレシピをフィルタリングする必要があります。ユーザーがカテゴリをチェックするときに、チェックされたカテゴリIDの配列を受け取り、そのようなレシピ:レールでカテゴリをフィルタリングする

scope :filter, -> (category_ids){ includes(:categories).where(categories: {id: category_ids}) if category_ids.present? } 

Recipe.filter(params_index[:category_ids]) 

プライベートレシピコントローラでこのスコープを使用

def params_index 
    params.permit(category_ids: []) 
end 

問題は、カテゴリidのいずれかがユーザーによって渡されたcategory_idsと一致する場合です。たとえば、ユーザーが朝食とサラダを選択した場合、すべての朝食とすべてのサラダが返されますが、朝食とサラダ。 activerecordでこれを行うことはできますか?dbへのクエリのように見えますか?私はレール5とpostgresqlを使用しています。あなたはgrouphavingでこれを達成することができますあなたの助け)

+0

'グループ(:recipe_id)を.having( "COUNT(*)=?"、category_ids.sizeを)'? – potashin

+0

私は置き換えました:recipe _idに:idとそれは正常に動作します。ありがとう!とても!) –

答えて

1

の希望:

scope :filter, -> (category_ids) { 
    return unless category_ids.present? 
    includes(:categories).where(categories: { id: category_ids }) 
         .group(:id).having("count(*) = ? ", category_ids.size) 
} 
関連する問題