Last active
January 9, 2024 11:36
-
-
Save RichOrElse/40bba8c03bed1a7255d0cc518cc0070c to your computer and use it in GitHub Desktop.
Faster SQL search with Union operation in Ruby on Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationRecord | |
# ... | |
scope :union, ->(*others) { from_unions(self, *others) } | |
def self.from_unions(*relations) | |
subquery = relations.map(&:arel).inject(:union) | |
unscoped.from subquery.as(table_name) | |
end | |
# ... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Book < ApplicationRecord | |
# ... | |
scope :search, ->(q) { | |
where(ean: q).union( | |
matching_title(q), | |
matching_description(q), | |
matching_author(q) | |
) | |
} | |
# ... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Book < ApplicationRecord | |
belongs_to :author | |
scope :old_search, ->(q) { | |
where(ean: q) | |
.or matching_title(q) | |
.or matching_description(q) | |
.or matching_author(q) | |
} | |
scope :matching_title, ->(q) { where(table[:title].matches("%#{q}%")) } | |
scope :matching_description, ->(q) { where(table[:description].matches("%#{q}%")) } | |
scope :matching_author, ->(q) { left_joins(:author).merge(Author.matching_name(q)) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment