LoginSignup
13
5

More than 5 years have passed since last update.

RailsでDBに格納したテキストをlocaleに応じていい感じに取り出す方法

Last updated at Posted at 2015-10-12

DBに文言を格納するけど、localeに応じて日本語と英語を出し分けたいケースがありました。

ベースのやりかたはこちらの記事を参考にしています。

Railsの多言語化対応 I18nのやり方を整理してみた!【国際化/英語化】

「(6)DBに格納されている文字列の多言語化」のケースです。

DBの様子

テーブルにこんな感じで値を格納しているとします。

#storesテーブル
+------+-------------+---------------+
|  id  | name_en     |  name_ja      |
+------+-------------+---------------+
|   1  | Hoge Store  | ほげストア      |
+------+-------------+---------------+

ふつうに出力すると

ストレートに出力すると、こんな感じ。

#views/stores/show.html.haml
%h1
  - if(I18n.locale==:ja)
    = @store.name_ja
  - else
    = @store.name_en

ちょっとがんばって動的にlocaleを読み込むと、

#views/stores/show.html.haml
%h1
  = @store.send("name_#{I18n.locale}")

きれいになりました。

しかしいろんなところにこれ書くのは大変。

モデルのメソッドにしたらいいじゃない

というわけで、モデル側でこんな感じにメソッドを定義してみる。

# models/stores.rb
class Store < ActiveRecord::Base    
  def name
    self.send("name_#{I18n.locale}")
  end
end

するとviewではいつもどおり呼び出すだけで、いい具合に翻訳されて出てくる。

#views/stores/show.html.haml
%h1
  = @store.name

便利!

13
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5