I am looking for a clean way to construct a query based upon an array of params it receives. To give some context a user can select filters to return the desired set of objects based upon the category name
class Category < ActiveRecord::Base
has_many :bike_categories
has_many :bikes, through: :bike_categories
end
class BikeCategory < ActiveRecord::Base
# Holds bike_id and category_id to allow multiple categories to be saved per image, as opposed to storing an array of objects in one DB column
belongs_to :bike
belongs_to :category
end
class Bike < ActiveRecord::Base
has_many :bike_categories, dependent: :destroy
has_many :categories, through: :bike_categories
end
So in my case filtering categories for Bikes
(Mens, Womens, Mountain Bike, Hybrid).
It is the case that a Bike could have more than 1 category
So a user could select just mens, but also want to see Mens Mountain Bikes, in this case I would only want Bikes that have the categories Mens and Mountain Bikes
Currently i have
class Bike < ActiveRecordBase
def self.search(params)
bikes = joins(:categories)
bikes = bikes.where(categories: { name: params[:name] }) if params[:name].present?
end
end
I understand that I can chain queries so .where(param: value1).where(param: value2)
or that the array can be passed through
bikes.where(categories: { name: [params[:name]] }) if params[:name].present?
Which would perform an IN
statement if i remember correctly.
How could I go about constructing this query so that I get the results I require
Thanks
Update
For example I have the following setup
Bike
id: 1 title: 'Bike 1'
category
id: 1 name: 'Mens'
id: 2 name: 'Womens'
id: 3 name: 'Mountain Bike'
id: 4 name: 'Hybrid'
bike_categories
id: 1 bike_id: 1 :category_id: 2
id: 2 bike_id: 1 :category_id: 2
So I have a Bike that has two categories, Womens, Mountain Bike
and I would like to just find that record