Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment