Search functionality rails 4
<p>I have a current implementation that allows me to filter my search results by category name</p>

<pre><code>class Category &lt; ActiveRecord::Base
  has_many :bike_categories
  has_many :bikes, through: :bike_categories
end

class BikeCategory &lt; 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 &lt; ActiveRecord::Base
  has_many :bike_categories, dependent: :destroy
  has_many :categories, through: :bike_categories
end

Model

def self.search(params)
  includes_categories(params[:name])
end

def self.includes_categories(category_names)
  joins(:categories)
  .where(categories: { name: category_names })
  .group('bikes.id')
  .having("count(*) = ?", category_names.size)
end
</code></pre>

<p>So if i have the following data</p>

<pre><code>Bike
id: 1 title: 'Bike 1'
id: 2 title: 'Bike 2'

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 # Womens, Mountain Bike
id: 2 bike_id: 1 :category_id: 3 

id: 3 bike_id: 2 :category_id: 2 # Womens, Hybrid
id: 4 bike_id: 2 :category_id: 4
</code></pre>

<p>In my filter if i choose <code>Womens</code> and <code>Mountain Bikes</code> i get all bikes with the categories <code>Womens, Mountain Bikes</code>, so in this example just the one result.</p>

<p>However I then would like to go one step further and select another category, <code>hybrid</code> (so i would select filters <code>Womens, Mountain Bikes, Hybrid</code>) and would like all bikes that have either <code>Womens, Mountain Bikes</code> and <code>Womens, Hybrid</code>, so in this instance I should get the 2 results returned</p>

<p>How could i modify this query to allow for this ?</p>

<p>Thanks</p>