Created
October 29, 2009 03:55
-
-
Save localshred/221131 to your computer and use it in GitHub Desktop.
It always bugged me that there isn't really a "rails-style" way to do like syntaxes with active record. So, one day while building a keyword search on the users table, I decided to roll my own. I've thought about making this more ActiveRecord friendly, bu
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
# Build a condition array from the provided keywords and a specific set of fields to search on | |
# Take out any keywords that are 2 chars or less | |
def self.find_by_keywords(keywords) | |
# Columns to do keyword searching on | |
fields = %w{ user_name email } | |
# Strip all words 2 chars or less, then split into an array | |
keywords = keywords.gsub(/\b\S{1,2}\b/, "").strip.downcase.split(/\s+/) | |
unless (keywords.nil? || keywords.empty?) | |
# Build the initial conditional string with bindings in place, | |
# then throw it into the newly created conditional array | |
conditions = fields.collect {|f| ["LOWER(#{f}) LIKE ?"]*keywords.size }.join(" OR ").to_a | |
# Loop number of fields, then each keyword, placing the actual bound parameter into the conditional array | |
fields.size.times {|i| keywords.each {|kw| conditions << "%"+kw+"%" } } | |
self.all(:conditions => conditions) | |
else | |
nil | |
end | |
end | |
#----- | |
# Placing the above code in app/models/user.rb allows you to do safe keyword searching on the user table | |
class UsersController > ApplicationController | |
... | |
def search | |
@users = User.find_by_keywords(params[:keywords]) | |
... | |
end | |
... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment