Skip to content

Instantly share code, notes, and snippets.

@erpe
Last active December 20, 2015 18:18
Show Gist options
  • Save erpe/6174427 to your computer and use it in GitHub Desktop.
Save erpe/6174427 to your computer and use it in GitHub Desktop.
using chained scopes for facetted querying
class Program < ActiveRecord::Base
belongs_to :associated_school
scope :active, -> { where("active = ?", true) }
scope :inactive, -> { where("active = ?", false)}
scope :in_country, ->(country) {
joins(associated_school:
{school: :address}
).where(addresses:
{ country_code: country }
)
}
scope :with_language, ->(lang) { where("language=?", lang) }
end
class ProgramsController < ApplicationController
def index
@programs = params.empty? ? Program.active : find_scoped(params)
end
private
def find_scoped(args)
@_programs = Program.active
available_scopes = %w{ in_country with_language }
available_scopes.each do |scope|
if args[scope] && !args[scope].empty?
@_programs = @_programs.send(scope, args[scope] )
end
end
@_programs
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment