Skip to content

Instantly share code, notes, and snippets.

@anithri
Created October 12, 2012 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anithri/3881265 to your computer and use it in GitHub Desktop.
Save anithri/3881265 to your computer and use it in GitHub Desktop.
Match only projects that have all of the given project_types
class Project < ActiveRecord::Base
has_and_belongs_to_many :project_types
scope :has_any_project_types, ->(*project_types) do
joins(:project_types).
where("project_types.id IN (?)", project_types)
end
scope :has_all_project_types, ->(*project_types) do
joins(:project_types).
where("project_types.id IN (?)", project_types).
group("projects.id").
having("count(*)=?", project_types.length)
end
end
#Should get list of projects having any of the listed project_types
Project.has_any_project_types(4,6).all #Works as Expected
#Should get list of projects having all of the listed project_types
Project.has_all_project_types(4,6).all #Does not work as expected, does work as has_any_project_types.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment