A simple search in a Globalize3 table in Rails

I am looking to implement a simple search function using the glossy mark for Ruby on Rails. Since the model translations are stored in a separate table, the code below does not work, because the product table no longer has the: name field. How to customize the code below to correctly execute the search function?

products_controller.rb

 @products = Product.search(params[:search]).all

index.html.erb

 <%= form_tag products_path, method: :get do %>   
   <%= text_field_tag :search, params[:search] %>
   <%= submit_tag "Search", name: nil %>      
 <% end %>

model

class Product < ActiveRecord::Base
  translates :name
  attr_accessible :name, :price, :released_at

  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      scoped
    end
  end
end
+5
source share
1 answer

You are lucky, I recently addressed the same problem!

Fortunately for you, the answer is pretty simple. You can use the class method with_translationsto enable translations for a given set of locales.

Here is the code:

def with_translations(*locales)
  locales = translated_locales if locales.empty?
  includes(:translations).with_locales(locales).with_required_attributes
end

Include it in your method search:

def self.search(search)
  if search
    with_translations.where('name LIKE ?', "%#{search}%")
  else
    with_translations
  end
end

That should do it.

: locales with_translations, , , , .

+14

All Articles