I have habtm relation between products and colors. When I preform a query on products that are "red" and "black" I want it to return product that have "red" AND "black" associations not "red" OR "black"
This is my scope for this query:
scope :items_design_filter_color, -> (colors) { joins(:colors).where('colors.id' => colors.to_i) unless colors.nil? }
colors params
params[:colors] = ["1", "2"]
colors table is just id and name columns
Calling my scopes:
@products =
Kaminari.paginate_array(ItemsDesign.items_design_by_category(@category.subtree_ids)
.items_design_filter_color(params[:colors])
.items_design_filter_sort(sort)
.items_design_filter_editors_pick(params[:editors_pick])
.items_design_filter_sold_out(params[:sold_out])
.items_design_filter_style(params[:style])
.items_design_filter_store(params[:store])
.items_design_filter_price(params[:low_end], params[:high_end]))
.page(params[:page]).per(48)
this is my attempt at using one of the answers bellows method within my scope:
scope :items_design_by_category, -> (category) { joins(:items_categories).where('items_categories.id' => category) }
scope :items_design_filter_color, -> (colors) { joins(:colors).where(colors: {id: colors}).each.select do |item|
(item.colors.map(&:id) & colors).size == colors.size
end unless colors.nil? }
scope :items_design_filter_style, -> (styles) { where('items_style_id' => styles) unless styles.nil? }
scope :items_design_filter_store, -> (stores) { where('store_id' => stores) unless stores.nil? }
scope :items_design_filter_editors_pick, -> (editors_pick) { where('editors_pick' => TRUE) unless editors_pick.nil? }
scope :items_design_filter_sold_out, -> (sold_out) { where('sold_out' => 'n') unless sold_out.nil? }
scope :items_design_filter_price, -> (lowend, highend) { where('price_as_decimal' => lowend..highend) unless lowend.nil? }
scope :items_design_filter_sort, -> (sort) { order(sort) unless sort.nil? }