问题
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