Skip to content

Commit 972b9d7

Browse files
committed
Extract search logic to UserSearch model
1 parent 0136727 commit 972b9d7

File tree

2 files changed

+39
-32
lines changed

2 files changed

+39
-32
lines changed

app/controllers/users_controller.rb

+1-32
Original file line numberDiff line numberDiff line change
@@ -288,43 +288,12 @@ def activate_account
288288
end
289289

290290
def search_users
291-
292291
term = (params[:term] || "").strip.downcase
293292
topic_id = params[:topic_id]
294293
topic_id = topic_id.to_i if topic_id
295294

296-
sql = "select username, name, email from users u "
297-
if topic_id
298-
sql << "left join (select distinct p.user_id from posts p where topic_id = :topic_id) s on
299-
s.user_id = u.id "
300-
end
301-
302-
if term.length > 0
303-
sql << "where username_lower like :term_like or
304-
to_tsvector('simple', name) @@
305-
to_tsquery('simple',
306-
regexp_replace(
307-
regexp_replace(
308-
cast(plainto_tsquery(:term) as text)
309-
,'\''(?: |$)', ':*''', 'g'),
310-
'''', '', 'g')
311-
) "
312-
313-
end
295+
results = UserSearch.search term, topic_id
314296

315-
sql << "order by case when username_lower = :term then 0 else 1 end asc, "
316-
if topic_id
317-
sql << " case when s.user_id is null then 0 else 1 end desc, "
318-
end
319-
320-
sql << " case when last_seen_at is null then 0 else 1 end desc, last_seen_at desc, username asc limit(20)"
321-
322-
results = User.exec_sql(sql, topic_id: topic_id, term_like: "#{term}%", term: term)
323-
results = results.map do |r|
324-
r["avatar_template"] = User.avatar_template(r["email"])
325-
r.delete("email")
326-
r
327-
end
328297
render :json => results
329298
end
330299

app/models/user_search.rb

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class UserSearch
2+
3+
def self.search term, topic_id
4+
sql = "select username, name, email from users u "
5+
if topic_id
6+
sql << "left join (select distinct p.user_id from posts p where topic_id = :topic_id) s on
7+
s.user_id = u.id "
8+
end
9+
10+
if term.length > 0
11+
sql << "where username_lower like :term_like or
12+
to_tsvector('simple', name) @@
13+
to_tsquery('simple',
14+
regexp_replace(
15+
regexp_replace(
16+
cast(plainto_tsquery(:term) as text)
17+
,'\''(?: |$)', ':*''', 'g'),
18+
'''', '', 'g')
19+
) "
20+
21+
end
22+
23+
sql << "order by case when username_lower = :term then 0 else 1 end asc, "
24+
if topic_id
25+
sql << " case when s.user_id is null then 0 else 1 end desc, "
26+
end
27+
28+
sql << " case when last_seen_at is null then 0 else 1 end desc, last_seen_at desc, username asc limit(20)"
29+
30+
results = User.exec_sql(sql, topic_id: topic_id, term_like: "#{term}%", term: term)
31+
results = results.map do |r|
32+
r["avatar_template"] = User.avatar_template(r["email"])
33+
r.delete("email")
34+
r
35+
end
36+
end
37+
38+
end

0 commit comments

Comments
 (0)