Skip to content

Commit 43bcc2e

Browse files
authored
Merge pull request #1720 from codidact/0valt/387/post-title-search
2 parents 1633fd6 + 3062a26 commit 43bcc2e

5 files changed

Lines changed: 20 additions & 4 deletions

File tree

app/models/application_record.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ class ApplicationRecord < ActiveRecord::Base
22
self.abstract_class = true
33

44
def self.fuzzy_search(term, **cols)
5-
sanitized = sanitize_for_search term, **cols
5+
sanitized = sanitize_for_search(term, **cols)
66
select(Arel.sql("`#{table_name}`.*, #{sanitized} AS search_score"))
77
end
88

99
def self.match_search(term, **cols)
10-
sanitized = sanitize_for_search term, **cols
10+
sanitized = sanitize_for_search(term, **cols)
1111
select(Arel.sql("`#{table_name}`.*, #{sanitized} AS search_score")).where(sanitized)
1212
end
1313

app/models/post.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def self.accessible_to(user)
7676
# @param term [String] the search term
7777
# @return [ActiveRecord::Relation<Post>]
7878
def self.search(term)
79-
match_search term, posts: :body_markdown
79+
match_search term, posts: [:body_markdown, :title]
8080
end
8181

8282
def self.by_slug(slug, user)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# initial post FTS did not include titles
2+
class AddPostTitlesToPostsFts < ActiveRecord::Migration[7.2]
3+
def change
4+
remove_index :posts, :body_markdown, if_exists: true, type: :fulltext
5+
add_index :posts, [:body_markdown, :title], if_not_exists: true, type: :fulltext
6+
end
7+
end

db/schema.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@
507507
t.datetime "locked_at", precision: nil
508508
t.datetime "locked_until", precision: nil
509509
t.index ["att_source"], name: "index_posts_on_att_source"
510-
t.index ["body_markdown"], name: "index_posts_on_body_markdown", type: :fulltext
510+
t.index ["body_markdown", "title"], name: "index_posts_on_body_markdown_and_title", type: :fulltext
511511
t.index ["category_id"], name: "index_posts_on_category_id"
512512
t.index ["close_reason_id"], name: "index_posts_on_close_reason_id"
513513
t.index ["community_id"], name: "index_posts_on_community_id"
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
require 'test_helper'
2+
3+
class ApplicationRecordTest < ActiveSupport::TestCase
4+
test 'fuzzy_search should correctly search records' do
5+
results = Post.fuzzy_search('Q2', posts: [:body_markdown, :title]).map(&:id)
6+
post_ids = posts.select { |p| /^Q\d+/.match?(p.title) }.map(&:id)
7+
assert(post_ids.all? { |id| results.include?(id) })
8+
end
9+
end

0 commit comments

Comments
 (0)