Skip to content

Instantly share code, notes, and snippets.

@agraves
Created February 11, 2013 03:05
Show Gist options
  • Save agraves/4752183 to your computer and use it in GitHub Desktop.
Save agraves/4752183 to your computer and use it in GitHub Desktop.
UserSearch refactor
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
@agraves
Copy link
Author

agraves commented Feb 11, 2013

I think @blowmage's fork is an improvement over what I produced. See it here:

https://gist.github.com/blowmage/4755700

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment