From 3e3aa6a126fae6dcdf767d1bc69573a2c8b38bf4 Mon Sep 17 00:00:00 2001 From: Matchu Date: Wed, 26 Jul 2023 11:15:35 -0700 Subject: [PATCH] Move Item name search logic to model scope --- app/models/item.rb | 8 ++++++++ app/models/item/search/query.rb | 9 +++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/app/models/item.rb b/app/models/item.rb index aee1a7df..333f016c 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -47,6 +47,14 @@ class Item < ActiveRecord::Base scope :with_closet_hangers, -> { joins(:closet_hangers) } + scope :name_includes, ->(value, locale = I18n.locale) { + Item.joins(:translations).where('locale = ?', locale). + where('name LIKE ?', '%' + Item.sanitize_sql_like(value) + '%') + } + scope :name_excludes, ->(value, locale = I18n.locale) { + Item.joins(:translations).where('locale = ?', locale). + where('name NOT LIKE ?', '%' + Item.sanitize_sql_like(value) + '%') + } scope :is_nc, -> { i = Item.arel_table condition = i[:rarity_index].in(Item::NCRarities).or(i[:is_manually_nc]) diff --git a/app/models/item/search/query.rb b/app/models/item/search/query.rb index 4ac67c7b..898d768c 100644 --- a/app/models/item/search/query.rb +++ b/app/models/item/search/query.rb @@ -75,12 +75,9 @@ class Item end def to_query - base = Item.joins(:translations).where('locale = ?', @locale) - if @is_positive - base.where('name LIKE ?', '%' + Item.sanitize_sql_like(@value) + '%') - else - base.where('name NOT LIKE ?', '%' + Item.sanitize_sql_like(@value) + '%') - end + @is_positive ? + Item.name_includes(@value, @locale) : + Item.name_excludes(@value, @locale) end def to_s