Rails 4多域应用程序,为每个域i18n语言环境设置语言环境

在Rails 4多域应用程序中,我需要一组针对每个域的4种语言的区域设置文件(总共3个域)。

一些翻译在域之间重叠,但其中一些是非常具体的,所以我在想一个有点像这样的结构:

config/locales/en.yml ..fr.yml ..de.yml ..it.yml #is picked up by all domains config/locales/domain1/en.yml ..fr.yml ..de.yml ..it.yml #is picked up by domain 1 config/locales/domain2/en.yml ..fr.yml ..de.yml ..it.yml #is picked up by domain 2 config/locales/domain3/en.yml ..fr.yml ..de.yml ..it.yml #is picked up by domain 3 

这可能在Rails 4中吗? 如果是这样的话,最好的方法是什么呢?

config/application您将拥有:

 some_domain = Rails.root.basename.to_s # this will give us "myapp.com" if the app is in "/var/www/myapp.com" config.i18n.load_path += Dir[Rails.root.join('config', 'locales', some_domain, '*.{rb,yml}').to_s] 

这将仅加载所需的文件,并使用后面的数据覆盖任何重复的键,但我没有测试该位。

请尝试使用i18n-active_record .in,我们可以将它存储在database中的所有locales中。

在这个gem中他们使用的translation模型没有关系,在你的情况下,你可以创建relationdomain之间的relation ,然后你可以存储所有语言环境与基于domain的时候,你可以覆盖默认的gem方法。

==>您的密钥应包含使用域名来查找域名,或者您可以使用其他方式获取域名,如在thread或环境中,您可以保存您的价值。

#my guess key应该是login-label-test.com domain = Domain.where(:name => namespace.split(“ – ”)。last).first

在gem内部,他们发现translation只是覆盖该方法请尝试。

我不确定请尝试一次

首先将您的locale文件迁移到db

 require 'yaml' namespace :locale do desc "Copy translations from yml yo db. Non-overwriting." task :yml_to_db, [:environment, :locale,:domain] => :environment do |t, args| info = YAML::load(IO.read("#{Rails.root}/config/locales/#{args[:locale]}-#{args[:domain]}.yml")) domain = Domain.where(:name => args[:domain]).first info["#{args[:locale]}"].each do |key, value| translation = domain.translations.where(:key => key) domain.translations.create!(:key => key, :value => value, :locale => args[:locale]) if translation.blank? end end end 

我试图覆盖gem中的一个方法:

 require 'active_record' module I18n module Backend class ActiveRecord class Translation < ::ActiveRecord::Base belongs_to :domain TRUTHY_CHAR = "\001" FALSY_CHAR = "\002" self.table_name = 'translations' serialize :value serialize :interpolations, Array def lookup(keys, *separator) # in your keys should contain use domain name for find the domain or you can use some other way to get the domain name like in thread or env you can save your value. column_name = connection.quote_column_name('key') keys = Array(keys).map! { |key| key.to_s } unless separator.empty? warn "[DEPRECATION] Giving a separator to Translation.lookup is deprecated. " << "You can change the internal separator by overwriting FLATTEN_SEPARATOR." end namespace = "#{keys.last}#{I18n::Backend::Flatten::FLATTEN_SEPARATOR}%" # my guess key should be login-label-test.com domain = Domain.where(:name => namespace.split("-").last).first where("#{column_name} IN (?) OR #{column_name} LIKE ?", keys, namespace).where(:id => domain.id) end end end end 

请尝试这样。