0

I have a tables with content in two languages. Then I have a column called 'language' to distinguish.Now I use I18n to do multi languages website.So, how can I get content in database with current language?

I think that if I can set the default_scope of model accoding to the language, or load different models the same name.

Thank you!

Alan.Wang
  • 9
  • 1
  • Did you look at [Rails: store translations in database](http://stackoverflow.com/questions/1346939/rails-store-translations-in-database) – Wand Maker Jan 07 '16 at 08:45

2 Answers2

0

You can use a URL parameter to set the application locale for a request, for example:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_locale
 
  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end
end

Find the model by current locale:

YourContent.where(name: some_name, language: I18n.locale)

and use the t method in views with your strings files since you have the application locale set.

The docs have a few other examples.

Yes, you can use default_scope { language: I18n.locale } to omit the extra where, but be aware of the caveats of default_scope.

Community
  • 1
  • 1
p4sh4
  • 3,292
  • 1
  • 20
  • 33
0

If you want to switch to different table conditionally for same model, you can use ActiveRecord::Base.table_name class method.

Example:

cTable4 ❯ rails c -e production
Running via Spring preloader in process 60375
Loading production environment (Rails 4.2.4)
irb(main):001:0> Book.first
  Book Load (0.1ms)  SELECT  "books".* FROM "books"  ORDER BY "books"."id" ASC LIMIT 1
=> #<Book id: 1, name: "ELoquent Ruby", author: "Russ", year: "2011", created_at: "2016-01-07 08:40:47", updated_at: "2016-01-07 08:40:47">
irb(main):002:0> Book.table_name = 'titles'
=> "titles"
irb(main):003:0> Book.first
  Book Load (0.2ms)  SELECT  "titles".* FROM "titles"  ORDER BY "titles"."id" ASC LIMIT 1
=> #<Book id: 1, title: "Practical OOD Ruby", author: "Sandi Metz">
irb(main):004:0>
Babar Al-Amin
  • 3,939
  • 1
  • 16
  • 20