Attributes translated with globalize gem do not work with search form

558 Views Asked by At

I am using this gem to translate the attributes of my model

This is my model:

class Category < ActiveRecord::Base
  translates :name

  Globalize.fallbacks = {:es => [:es, :en, :pt], :en => [:en, :es, :pt], :pt => [:pt, :es, :en]}
  globalize_accessors
end

I have a form with a search to search by name

but this doesn't work for me because when I bring my data from my database by the model, I don't have my name attribute

  def fetch_categories
    I18n.locale = @language

    categories = Category.where(event_id: @event.id).order("#{sort_column} #{sort_direction}")
    categories = categories.page(page).per_page(per_page)
    if params[:search][:value].present?
      categories = categories.where("name like :search", search: "%#{params[:search][:value]}%")
    end
    categories
  end

categories returns me

#<ActiveRecord::Relation [#<Category id: 1, client_id: 1, event_id: 1, color: "#265BBD">, #<Category id: 2, client_id: 1, event_id: 1, color: "#E35274">]>

How can I get the name attribute in my query?

I have my categories and category_translations tables

1

There are 1 best solutions below

0
José Alejandro Cortés Segura On

I finally found the solution, it's simple:

  def fetch_categories
    I18n.locale = @language

    categories = Category.joins(:translations).where(event_id: @event.id).order("#{sort_column} #{sort_direction}")
    categories = categories.page(page).per_page(per_page)
    if params[:search][:value].present?
      categories = categories.where("category_translations.name like :search", search: "%#{params[:search][:value]}%")
    end
    categories
  end