1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

背景

  • 業務中にtable_name_prefixというメソッドを利用したファイルがモデル層にあった。
  • 初見だったのでちょっと調べてみたので記録しておく

table_name_prefixとは?

Railsのモデルが使用するテーブル名に自動的にプレフィックス(接頭辞)を追加するための設定メソッド

例えば、こういうモデルがあるとします

app/models/user.rb
class User < ApplicationRecord
end

当たり前ですが、この場合はusersテーブルを参照します。

次はこのように名前空間をつけてみます

app/models/user.rb
class Service::User < ApplicationRecord
end

これでもusersテーブルを参照します。

この状態でtable_name_prefixを利用すると

app/models/service.rb
# ここではActiveRecordは継承していません
module Service
  def self.table_name_prefix
    'service_'
  end
end
app/models/service/user.rb
class Service::User < ApplicationRecord
end

この場合、Service::Userモデルはservice_usersテーブルを参照するようになります

仕組み

Railsはモデルのテーブル名を決定する際、以下の順序で処理を行います:

  1. モデルの名前空間(module)にtable_name_prefixが定義されているか確認
  2. 定義されていれば、その戻り値をテーブル名の先頭に付与
  3. モデル名を複数形にしてテーブル名を生成

つまりService::Userの場合:

  • Serviceモジュールのtable_name_prefix'service_'を返す
  • モデル名Userが複数形usersになる
  • 結果:service_users

ユースケース

機能ごとのテーブル分離

大規模なアプリケーションで機能ごとにテーブルをグループ化したい場合に便利です。

# 決済関連
payment_orders
payment_transactions
payment_refunds

# 通知関連
notification_settings
notification_logs

レガシーDBとの連携

既存のDBスキーマに特定のプレフィックスがついている場合、Railsの命名規則に合わせるのではなく、既存のテーブル名に合わせることができます。

まとめ

  • table_name_prefixは名前空間配下のモデルが参照するテーブル名に接頭辞を自動付与する
  • モジュールに定義することで、配下の全モデルに適用される

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?