本文介绍了使用Tyre和Globalize3进行i18n搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用globalize3 gem(https://github.com/svenfuchs/globalize3)的网站,目前我正在添加Tire宝石以进行站点搜索.

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.

推荐答案

您必须将所有翻译编入索引:

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

这篇关于使用Tyre和Globalize3进行i18n搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 05:14