mirror of
https://github.com/scinote-eln/scinote-web.git
synced 2025-02-07 07:26:20 +08:00
53 lines
1.5 KiB
Ruby
53 lines
1.5 KiB
Ruby
module SearchableModel
|
|
extend ActiveSupport::Concern
|
|
|
|
included do
|
|
|
|
# Helper function for relations that
|
|
# adds OR ILIKE where clause for all specified attributes
|
|
# for the given search query
|
|
scope :where_attributes_like, ->(attributes, query) do
|
|
attrs = []
|
|
if attributes.blank? or query.blank?
|
|
# Do nothing in this case
|
|
elsif attributes.is_a? Symbol
|
|
attrs = [attributes.to_s]
|
|
elsif attributes.is_a? String
|
|
attrs = [attributes]
|
|
elsif attributes.is_a? Array
|
|
attrs = attributes.collect { |a| a.to_s }
|
|
else
|
|
raise ArgumentError, ":attributes must be an array, symbol or string"
|
|
end
|
|
|
|
if query.is_a? Array
|
|
|
|
unless attrs.empty?
|
|
where_str =
|
|
(attrs.map.with_index do |a, i|
|
|
"(trim_html_tags(#{a})) ILIKE ANY (array[ :t#{i}]) OR "
|
|
end
|
|
).join[0..-5]
|
|
vals = (attrs.map.with_index do |_, i|
|
|
["t#{i}".to_sym, query]
|
|
end
|
|
).to_h
|
|
|
|
return where(where_str, vals)
|
|
end
|
|
else
|
|
unless attrs.empty?
|
|
where_str =
|
|
(attrs.map.with_index do |a, i|
|
|
"(trim_html_tags(#{a})) ILIKE :t#{i} OR "
|
|
end
|
|
).join[0..-5]
|
|
vals = (attrs.map.with_index { |_, i| ["t#{i}".to_sym, query.to_s] })
|
|
.to_h
|
|
|
|
return where(where_str, vals)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|