Skip to content

Instantly share code, notes, and snippets.

@RichOrElse
Last active January 9, 2024 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichOrElse/40bba8c03bed1a7255d0cc518cc0070c to your computer and use it in GitHub Desktop.
Save RichOrElse/40bba8c03bed1a7255d0cc518cc0070c to your computer and use it in GitHub Desktop.
Faster SQL search with Union operation in Ruby on Rails
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
class Author < ApplicationRecord
has_many :books
scope :matching_name, ->(q) { where(table[:name].matches("%#{q}%")) }
end
class Book < ApplicationRecord
# ...
scope :search, ->(q) {
where(ean: q).union(
matching_title(q),
matching_description(q),
matching_author(q)
)
}
# ...
end
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