Skip to content

Instantly share code, notes, and snippets.

@launchkit-codes
Created December 17, 2014 15:48
Show Gist options
  • Select an option

  • Save launchkit-codes/20feb1f00e07092d8f36 to your computer and use it in GitHub Desktop.

Select an option

Save launchkit-codes/20feb1f00e07092d8f36 to your computer and use it in GitHub Desktop.
Using scope with HABTM
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
# :c can be an array of categories.
scope :by_categories, ->(c) { includes(:categories).where(categories: {id: c}) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment