LoginSignup
6
0

More than 1 year has passed since last update.

railsの中間テーブルのわかりやすい命名

Last updated at Posted at 2022-01-12

結論

railsの中間テーブルは多対多の関係にある2つのテーブルを結合した命名が多いが、関係性を表現する命名にするべき。

例:
usersテーブルとpoliciesテーブルの中間テーブルならagreementsテーブル(同意)
(観測範囲で言うと、policies_users, users_policies、user_policiesのような命名がされるケースが多い。)

詳しくは以下の記事に書かれています。

背景

リレーショナルデータベースは「多対多」の関係をうまく扱うことができないため、
中間テーブルという第3のテーブルを使って関係性を表現します。

これまでrailsの中間テーブルの命名は一般的には多対多の関係の2つのテーブルの名前を結合したものが多かったように思います。(例: policies_users)
これは、おそらくrails1,2時代にhas_and_belongs_to_manyメソッドでモデル間のリレーションを宣言するケースが多かったためです。

class User < ApplicationRecord
  has_and_belongs_to_many :policies
end

class Policy < ApplicationRecord
  has_and_belongs_to_many :users
end

has_and_belongs_to_manyを使用する場合、中間テーブルの命名にはルールがありました。
それは単語同士(今回の場合 users と policies)をアルファベット順に_で結合するというものです。(例: policies_users)
(なお余談ですが、has_and_belongs_to_manyを使用する場合、中間テーブルのモデルクラスは作成せず、migrationファイルを作成してテーブルだけ作成します。)

その慣習から今でも中間テーブルの命名として、2つのテーブルを結合したものが多くなっています。
ですが、今は御存知の通りhas_many :throughで多対多のリレーションシップを宣言するケースが大半です。

class User < ApplicationRecord
  has_many :agreements
  has_many :policies, through: :agreements
end

class Agreement < ApplicationRecord
  belongs_to :user
  belongs_to :policy
end

class Policy < ApplicationRecord
  has_many :agreements
  has_many :users, through: :agreements
end

has_many :throughの場合は中間テーブルに独自の名前を命名できるので、無思考に2つのテーブル名を結合するのではなく、よりわかりやすいテーブル名にするべきです。
ただし、books_authors、articles_tagsのようにそのまま結合したほうがわかりやすい場合もあるので、ケースバイケースです。
あとプロジェクトごとの命名規則もあると思うので、状況に応じて柔軟に決定してください。

なお、has_and_belongs_to_manyと、has_many :throughの違いは蛇足なので割愛しますが、以下の記事がわかりやすかったです。

メリット

中間テーブルに意味のある名前をつけるメリットはたくさんあると思います、まず可読性の向上、それによる保守性の向上。

また、インターフェースをカプセル化した時も、意味がわかりやす、より直感的になると思います。

User.rb
def agree(policy_id:)
  agreements.create!(policy_id: policy_id)
end

def agreeing_to_latest_policy?
  return false unless user_policy_latest_version = policies.maximum(:version)  
  user_policy_latest_version == Policy.maximum(:version)
end

お気づきの点がありましたら、ご気軽にご指摘ください。

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