Last active
December 20, 2015 18:18
-
-
Save erpe/6174427 to your computer and use it in GitHub Desktop.
using chained scopes for facetted querying
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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