Skip to content

Instantly share code, notes, and snippets.

@localshred
Created October 29, 2009 03:55
Show Gist options
  • Save localshred/221131 to your computer and use it in GitHub Desktop.
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
# 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