ruby on rails - How can I query my db for params by "and" instead of "or" -
ruby on rails - How can I query my db for params by "and" instead of "or" -
i have habtm relation between products , colors. when preform query on products "red" , "black" want homecoming product have "red" , "black" associations not "red" or "black"
this scope 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 id , name columns
calling 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 effort @ using 1 of answers bellows method within 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 |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? }
ok, ended getting way based on someones reply deleted. if want come , set reply give them credit. in meantime solved problem.
scope :items_design_filter_color, -> (colors) { color_ids = colors.map(&:to_i) unless colors.nil? includes(:colors).where(colors: {id: color_ids}).select |item| (item.colors.map(&:id) & color_ids).size == color_ids.size end unless colors.nil? }
ruby-on-rails activerecord scope has-and-belongs-to-many
Comments
Post a Comment