Guest User

Untitled

a guest
Apr 21st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. # Build a condition array from the provided keywords and a specific set of fields to search on
  2. # Take out any keywords that are 2 chars or less
  3. def self.find_by_keywords(keywords)
  4. # Columns to do keyword searching on
  5. fields = %w{ user_name email }
  6.  
  7. # Strip all words 2 chars or less, then split into an array
  8. keywords = keywords.gsub(/\b\S{1,2}\b/, "").strip.downcase.split(/\s+/)
  9. unless (keywords.nil? || keywords.empty?)
  10.  
  11. # Build the initial conditional string with bindings in place,
  12. # then throw it into the newly created conditional array
  13. conditions = fields.collect {|f| ["LOWER(#{f}) LIKE ?"]*keywords.size }.join(" OR ").to_a
  14.  
  15. # Loop number of fields, then each keyword, placing the actual bound parameter into the conditional array
  16. fields.size.times {|i| keywords.each {|kw| conditions << "%"+kw+"%" } }
  17. self.all(:conditions => conditions)
  18. else
  19. nil
  20. end
  21. end
  22.  
  23. #-----
  24.  
  25. # Placing the above code in app/models/user.rb allows you to do safe keyword searching on the user table
  26. class UsersController > ApplicationController
  27. ...
  28. def search
  29. @users = User.find_by_keywords(params[:keywords])
  30. ...
  31. end
  32. ...
  33. end
Add Comment
Please, Sign In to add comment