Skip to content

Commit 39ae0ab

Browse files
authored
Merge pull request #55 from amatsuda/messages_search
Extract search logic and template from messages#index
2 parents a852393 + a6155fb commit 39ae0ab

File tree

2 files changed

+23
-18
lines changed

2 files changed

+23
-18
lines changed

app/controllers/messages_controller.rb

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,13 @@ class MessagesController < ApplicationController
33

44
# GET /messages
55
def index
6-
query = params[:q]
7-
unless query
6+
if (query = params[:q])
7+
search query
8+
else
89
@messages = []
9-
return
1010
end
1111

12-
page = params[:page].to_i
13-
list_ids = get_list_ids(params)
14-
if list_ids.empty?
15-
raise "Need to select at least one list"
16-
end
17-
18-
# %> and <-> are defined by pg_trgm.
19-
# https://www.postgresql.org/docs/17/pgtrgm.html
20-
message_where = if Rails.env.production?
21-
Message.where('body %> ? AND list_id IN (?)', query, list_ids)
22-
.order(Arel.sql('body <-> ?', query))
23-
else
24-
Message.where('body LIKE ? AND list_id IN (?)', "%#{query}%", list_ids)
25-
end
26-
@messages = message_where.offset(page * PER_PAGE).limit(PER_PAGE)
12+
render :search
2713
end
2814

2915
# GET /messages/1
@@ -37,6 +23,7 @@ def show
3723
end
3824

3925
private
26+
4027
def get_list_ids(params)
4128
list_ids = []
4229
['ruby-talk', 'ruby-core', 'ruby-list', 'ruby-dev'].each do |name|
@@ -46,4 +33,22 @@ def get_list_ids(params)
4633
end
4734
list_ids
4835
end
36+
37+
def search(query)
38+
page = params[:page].to_i
39+
list_ids = get_list_ids(params)
40+
if list_ids.empty?
41+
raise "Need to select at least one list"
42+
end
43+
44+
# %> and <-> are defined by pg_trgm.
45+
# https://www.postgresql.org/docs/17/pgtrgm.html
46+
message_where = if Rails.env.production?
47+
Message.where('body %> ? AND list_id IN (?)', query, list_ids)
48+
.order(Arel.sql('body <-> ?', query))
49+
else
50+
Message.where('body LIKE ? AND list_id IN (?)', "%#{query}%", list_ids)
51+
end
52+
@messages = message_where.offset(page * PER_PAGE).limit(PER_PAGE)
53+
end
4954
end

0 commit comments

Comments
 (0)