translate database fields with rails

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I know about the built-in I18n in Rails, but how can I select a database field per locale?

My model structure is something like this:

title    #default (englisch) title_de #(german) title_it #(italian) 

In my template I want to be able to write only

<%= @model.title %> 

and should get the value in the right language.

Is there a plugin or a solution to use different fields per different locale settings with a structure like mine?

回答1:

Although your db architecture (different locales hardcoded as table columns) seems wrong to me, I think you can achieve what you want by adding a pseudo-field to your model, something along:

# example not tested class MyModel < ActiveRecord::Base   def localized_title(locale)     locale = locale == 'en' ? '' : '_' + locale     read_attribute("title#{locale}".to_sym")   end end 

Or, provided that you somehow make your current locale visible to your models, you can similarly overwrite the default title accessor method.

Edit: You can take a look at http://github.com/iain/translatable_columns, it seems pretty much compatible with your architecture....



回答2:

Try using:

http://github.com/joshmh/globalize2

It may require renaming your columns (to a different standard).



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