3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails5で日本語カラム名が簡単に使えるようになった

Last updated at Posted at 2018-02-12

Rails5になってマイグレーションのcommentが使えるようになりました。これを利用すると簡単に日本語カラム名が使えるようになります。

ちなみに現在対応しているDBMSはMySQLとPostgreSQLだけみたいです。

例えば以下のようなUserモデルを作ります

db/migrate/create_user.rb
class User < ActiveRecord::Migration[5.1]
  def change
    create_table :users, comment: "ユーザ" do |t|
      t.string :first_name, comment: '名'
      t.string :last_name, comment: '姓'
    end
  end
end

コメントで各attributeにアクセスできるように、以下のモジュールを作成します。

app/models/concerns/comment_attribute.rb
module CommentAttribute
  extend ActiveSupport::Concern

  def [](comment)
    attr_name = comment_to_attr_name(comment) || comment
    super(attr_name)
  end

  def []=(comment, value)
    attr_name = comment_to_attr_name(comment) || comment
    super(attr_name, value)
  end

  def comment_to_attr_name(comment)
    self.class.columns.find{|r| r.comment == comment }&.name
  end
end

Rails5から導入されたApplicationRecordにモジュールをincludします。

app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
+  include CommentAttribute
  self.abstract_class = true
end

これだけで、

user = User.new(first_name: "のび太", last_name: "野比")

# read
user["姓"] #=> "野比"
user["名"] #=> "のび太"

# write
user["名"] = "しずか"

簡単に日本語カラム名が使えるようになりました。

2018/05/04追記
よくつかうんでgem作ってみた。始めてのgem作成でしたがとりあえずリリースできたのでよかったら使ってください。
https://github.com/nizoraul/comment_attribute

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?