
On the Floor
has_foreign_language is a Ruby on Rails plugin by factor[e] that makes it easy to internationalize your database without mucking up your views and controllers or having to write a bunch of YAML. Just create fields for each locale you want to support in addition to your default field and has_foreign_language will automatically call the appropriate one based on the current locale.
Installation
Install it into your Rails application by running
script/plugin install git://github.com/factore/has_foreign_language.git
Example
First create your model:
script/generate model books title:string title_fr:string title_de:string author:string
Then specify which fields need to be internationalized in your model:
class Country < ActiveRecord::Base
has_foreign_language :title
end
Now let's create a book in the console and see how this works:
I18n.default_locale = "en"
b = Book.new(:title => "Slaughterhouse Five", :title_fr => "Abattoir Cinq", :title_de => "Schlachthof Fünf")
b.title # Slaughterhouse Five
I18n.locale = "fr"
b.title # Abattoir Cinq
I18n.locale = "de"
b.title # Schlachthof Fünf
Calling title on the model returns the appropriate column depending on which locale we're in. This also works when we change the attribute:
I18n.locale = "de"
b.title = "Etwas Anderes"
b # Book id: nil, title: "Slaughterhouse Five", title_fr: "Abattoir Cinq", title_de: "Etwas Anderes"
If you want to set or return the default language attribute while in a different locale, you can call it the way you would call any other. Assuming the default is "en", you would run:
b.title_en # Slaughterhouse Five
b.title_en = "Something Else" # Book id: nil, title: "Something Else", title_fr: "Abattoir Cinq", title_de: "Etwas Anderes"
Validations
Validations with has_foreign_language are easy. Just run the validation on the default field name and it will apply to whatever locale you're in.
class Country < ActiveRecord::Base
has_foreign_language :title
validates_presence_of :title
end
I18n.locale = "de"
b = Book.new(:title => "Etwas Anderes") # Book id: nil, title: nil, title_fr: nil, title_de: "Etwas Anderes"
b.valid? # true
I18n.locale = "en"
b.valid? # false
b.title = "Slaughterhouse Five"
b.valid? # true
Subscribe 
Follow us on
Twitter 
Archives
May 2013April 2013
March 2013
February 2013
January 2013
December 2012
November 2012
October 2012
September 2012
August 2012
July 2012
June 2012
May 2012
April 2012
March 2012
February 2012
January 2012
December 2011
November 2011
October 2011
September 2011
August 2011
July 2011
May 2011
April 2011
March 2011
February 2011
January 2011
December 2010
November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
May 2010
April 2010
March 2010
February 2010
January 2010
December 2009
November 2009
October 2009
September 2009
June 2009
March 2009
January 2009
December 2008
November 2008
September 2008
August 2008








Comments