Created
February 11, 2013 03:05
-
-
Save agraves/4752183 to your computer and use it in GitHub Desktop.
UserSearch refactor
This file contains hidden or 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
class UserSearch | |
def self.search(term, topic_id = nil) | |
scope = User.scoped | |
if topic_id | |
scope = scope.joins(" | |
LEFT JOIN ( | |
SELECT DISTINCT(posts.user_id) | |
FROM posts | |
WHERE topic_id = #{topic_id.to_i} | |
) s ON s.user_id = users.id | |
") | |
scope = scope.order('s.user_id IS NULL') | |
end | |
scope = scope.order(' | |
last_seen_at IS NULL ASC, | |
last_seen_at DESC, | |
username ASC | |
') | |
scope = scope.where(" | |
username_lower LIKE :term_like OR | |
TO_TSVECTOR('simple', name) @@ | |
TO_TSQUERY('simple', | |
REGEXP_REPLACE( | |
REGEXP_REPLACE( | |
CAST(PLAINTO_TSQUERY(:term) AS text) | |
,'\''(?: |$)', ':*''', 'g'), | |
'''', '', 'g') | |
)", term: term, term_like: "#{term.downcase}%") | |
scope.limit(20) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think @blowmage's fork is an improvement over what I produced. See it here:
https://gist.github.com/blowmage/4755700