i18n search using tire and Globalize3

这一生的挚爱 提交于 2019-12-11 03:36:42

问题


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:


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™.



来源:https://stackoverflow.com/questions/9951348/i18n-search-using-tire-and-globalize3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!