rails 本地化i18n

基础配置
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += %W(#{config.root}/lib/bootstrap)
config.i18n.locale = 'zh-CN'
config.i18n.default_locale = 'zh-CN'
上面配置之后其它不管文件名取为devise.zh-CN.yml还是simple_form.zh_CN.yml只要里面文件第一句为zh-CN:那么就会对应本地化。
产生两个方法i18n.t/l
单独读取本地化时采用上面的方法,然后层层剥去里面的结构
I18n.t("models." + model.to_s.underscore) 如果有多层则在到参数地方按照结构的层次往下加I18n.t("datatime."+'user.'+'name')这样达到目的

项目做的一个获取所有模型对应的本地化。
(1)使用ActiveRecord::Base.descendants获取所有模型名字
在lib文件下创建一个all_models.rb
# -*- encoding : utf-8 -*-
module Rails
def self.all_models
Rails.application.eager_load! if Rails.env != "production" rescue nil
ActiveRecord::Base.descendants
end
end
(2)创建所有模型本地化的实例,在前端直接使用
require './lib/all_models'
before_filter :get_all_models, only: [:new, :edit]
private
def get_all_models
@all_models = Rails.all_models.map do |model|
translation = I18n.t("models." + model.to_s.underscore)
if translation.include? 'translation missing'
nil
else
[translation,model.to_s]
end
end.compact.sort
end
<td><%= f.input :subject_class, collection: @all_models, label: false, :include_blank => "请选择", :input_html => {:class => "select2"} %></td>

使用yml文件进行初始化数据。
读取文件内容方式YAML.load_file("#{Rails.root}/config/database.yml")
读到的是一个hash。可以作为参数直接传给某个模型。这样就完成了创建。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值