2013-02-07 03:34:49 -06:00
|
|
|
class UserSearch
|
|
|
|
|
2013-02-07 05:50:59 -06:00
|
|
|
def self.search term, topic_id = nil
|
2013-02-07 04:54:55 -06:00
|
|
|
User.find_by_sql sql(term, topic_id)
|
2013-02-07 04:07:03 -06:00
|
|
|
end
|
|
|
|
|
2013-02-07 04:54:55 -06:00
|
|
|
private
|
|
|
|
|
2013-02-07 04:07:03 -06:00
|
|
|
def self.sql term, topic_id
|
2013-02-07 05:50:59 -06:00
|
|
|
sql = "select id, username, name, email from users u "
|
2013-02-07 03:34:49 -06:00
|
|
|
if topic_id
|
|
|
|
sql << "left join (select distinct p.user_id from posts p where topic_id = :topic_id) s on
|
|
|
|
s.user_id = u.id "
|
|
|
|
end
|
|
|
|
|
2013-02-07 05:50:59 -06:00
|
|
|
if term.present?
|
2013-02-07 04:59:25 -06:00
|
|
|
sql << "where username ilike :term_like or
|
2013-02-07 03:34:49 -06:00
|
|
|
to_tsvector('simple', name) @@
|
|
|
|
to_tsquery('simple',
|
|
|
|
regexp_replace(
|
|
|
|
regexp_replace(
|
|
|
|
cast(plainto_tsquery(:term) as text)
|
|
|
|
,'\''(?: |$)', ':*''', 'g'),
|
|
|
|
'''', '', 'g')
|
|
|
|
) "
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
sql << "order by case when username_lower = :term then 0 else 1 end asc, "
|
|
|
|
if topic_id
|
|
|
|
sql << " case when s.user_id is null then 0 else 1 end desc, "
|
|
|
|
end
|
|
|
|
|
|
|
|
sql << " case when last_seen_at is null then 0 else 1 end desc, last_seen_at desc, username asc limit(20)"
|
2013-02-07 04:54:55 -06:00
|
|
|
|
|
|
|
sanitize_sql_array(sql, topic_id: topic_id, term_like: "#{term}%", term: term)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.sanitize_sql_array *args
|
|
|
|
ActiveRecord::Base.send(:sanitize_sql_array, args)
|
2013-02-07 03:34:49 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|