Skip to content

Instantly share code, notes, and snippets.

@agoodman
Created August 5, 2011 20:40
Show Gist options
  • Save agoodman/1128462 to your computer and use it in GitHub Desktop.
Save agoodman/1128462 to your computer and use it in GitHub Desktop.
Ruby on Rails scope filtering
# Model:
#
# class Example < ActiveRecord::Base
# end
#
# Controller:
#
# class ExamplesController < ActionController::Base
# def index
# @examples = Example.filtered_scope(params[:filter])
# end
# end
#
# Query String Usage:
#
# /examples?filter[title]=value&filter[min_created_at]=2011-01-01
#
# Matches only examples with
# title equal to "value" AND
# created_at greater than or equal to 2011-01-01
class ActiveRecord::Base
def self.filtered_scope(filter)
filtered_scope = self.scoped
if filter
for column in filter.keys
if self.column_names.include?(column)
filtered_scope = filtered_scope.where(column => filter[column])
else
name = column[4..column.length]
if self.column_names.include?(name)
if column[0..3]=='min_'
filtered_scope = filtered_scope.where(["#{name} >= ?",filter[column]])
elsif column[0..3]=='max_'
filtered_scope = filtered_scope.where(["#{name} <= ?",filter[column]])
end
end
end
end
end
filtered_scope
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment