Created
February 23, 2021 07:12
-
-
Save channainfo/f3af91945a42c303d4e9fe1546af7f1b to your computer and use it in GitHub Desktop.
Spree search with globalize by translated fields
This file contains hidden or 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
# spree/model/product.rb | |
def self.like_any_with_translation(fields, values) | |
tran_fields = if defined?(SpreeGlobalize) | |
fields.select{ |field| Spree::Product.translated_attribute_names.include?(field) } | |
else | |
[] | |
end | |
if tran_fields.blank? | |
like_any(fields, values) | |
else | |
like_any(fields - tran_fields , values).search_by_translated_fields(tran_fields, values) | |
end | |
end | |
def self.search_by_translated_fields(tran_fields, values) | |
conditions = tran_fields.product(values).map do |(field, value)| | |
Product::Translation.arel_table[field].matches("%#{value}%") | |
end | |
rel = joins(:translations).where(conditions.inject(:or)).distinct | |
rel.order(:name) if tran_fields.include?(:name) | |
end | |
def self.like_any(fields, values) | |
conditions = fields.product(values).map do |(field, value)| | |
arel_table[field].matches("%#{value}%") | |
end | |
where conditions.inject(:or) | |
end | |
def self.search_by_name(query) | |
if defined?(SpreeGlobalize) | |
joins(:translations).order(:name).where("LOWER(#{Product::Translation.table_name}.name) LIKE LOWER(:query)", query: "%#{query}%").distinct | |
else | |
where("LOWER(#{Product.table_name}.name) LIKE LOWER(:query)", query: "%#{query}%") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment