2

i have a site that uses globalize3 gem (https://github.com/svenfuchs/globalize3) and i'm currently adding the Tire gem to make site search.

How do i do to Index a table translations depending on the actual locale? right now the model that gets indexed only does with the default locale.

1 Answer 1

0

You'd have to index all the translations:

class Centre < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  mapping do
    indexes :title_en, :as => lambda { |post| I18n.locale = :en; post.title }
    indexes :title_es, :as => lambda { |post| I18n.locale = :es; post.title }
    indexes :title_jp, :as => lambda { |post| I18n.locale = :jp; post.title }
  end

end

This can become cumbersome if you support a lot of languages for a lot of attributes, you might have to resort to meta-programming:

class Centre < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  mapping do
    %w[en it jp].each do |locale|
      %w[title text].each do |attribute|
        class_eval<<-RUBY
          indexes :#{attribute}_#{locale}, :as => lambda { |post| I18n.locale = :#{locale}; post.#{attribute} }
        RUBY
      end
    end
  end

end

I didn't test the above code, it's just to give an idea, so make sure you understand it and it works before using it in your project, otherwise BAD THINGS WILL HAPPEN™.

2
  • got it, thanks for the approach, i was thinking on modifying the gem to consider the table _translations to the search, but this looks ok as well. thanks!
    – delagroove
    Aug 15, 2012 at 17:58
  • 1
    Note that the I18n.locale setting is global, so a request might end up with a different locale than it started with. Consider resetting the locale at the end of each lambda.
    – Matchu
    Jan 18, 2013 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.