Simple search on a Globalize3 table in Rails
Asked Answered
T

2

6

I am looking to implement a simple search function while using the globalize3 gem for Ruby on Rails. Since the translations of the model are stored in a separate table, the code below doesn't work as there is no longer a :name field in the products table. How can I adjust the code below to make the search function correctly?

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
Tortile answered 22/8, 2012 at 0:8 Comment(0)
I
17

You're in luck, I tackled exactly the same problem recently!

Luckly for you the answer is quite simple. You can use the class method with_translations to include translations for a given set of locales.

Here's 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 search method:

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

That should do it.

As an added note: you could add an optional locales parameter to the search method and pass it to with_translations to optionally narrow the search to terms in a particular language, say for example in the current locale.

Inclement answered 22/8, 2012 at 0:39 Comment(2)
using 5.0.1 of gloablize I get 'with_required_attributes is deprecated and will be removed in the next release of Globalize.'Shennashensi
In postgresql it also required to specify table name before column name.Excaudate
T
0

Solved ...

    def index
        if params[:search]
          @at = []
          @at = Array.new
          Article.translation_class.where("title LIKE ? OR description LIKE ?","%#{params[:search]}%","%#{params[:search]}%").all.each do |t|
            @at.push t.article_id
          end
          @articles = Article.where(id: @at).recent_first.paginate(page: params[:page], per_page: 5)
        else
          @articles = Article.all.recent_first.paginate(page: params[:page], per_page: 5)
        end
      end
Tamera answered 11/4, 2020 at 12:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.