Railsのリレーションについてです
usersテーブル
少し省略してあります。
カラム名 | 型 | 説明 |
---|---|---|
id | integer | 主キー(自動採番) |
userid | string | ユーザーID(ログイン用) |
password_digest | string | パスワード(Devise等) |
username | string | 表示名 |
followテーブル
カラム名 | 型 | 説明 |
---|---|---|
id | integer | 主キー |
follower_user_id | integer | フォローする側(自分) |
follow_user_id | integer | フォローされる側(相手) |
created_at | datetime | 作成日時(いつフォローしたか) |
updated_at | datetime | 更新日時 |
userモデル
class User < ApplicationRecord
# 自分がフォローしているユーザー
has_many :follows, foreign_key: :follower_user_id, dependent: :destroy
has_many :follow_users, through: :follows, source: :follow_user
# 自分をフォローしてくれるユーザー
has_many :reverse_follows, class_name: 'Follow', foreign_key: :follow_user_id, dependent: :destroy
has_many :follower_users, through: :reverse_follows, source: :follower_user
end
1つずつ解説
自分がフォローしているユーザー
# userモデル
has_many :follows, foreign_key: :follower_user_id, dependent: :destroy
-
follows
についてですが、このように書くことでRails
が自動でfollow
モデルを探してきてくれます。 -
foreign_key:
に関してですが、user_id
ではないので明示的に書きます。慣れていないのでかなりややこしいです。userモデル
のid
ですね多分。ですが、follows
テーブルにはuser_id
カラムがないので明示的にしています。
# userモデル
has_many :follow_users, through: :follows, source: :follow_user
-
follow_users
は メソッド名です。自分がフォローしているユーザー一覧が取得できます。 -
through: :follows
ですが、1つ目のやつのfollow
を実行します。 -
source: :follow_user
はどのカラムを使用するかです。
自分がフォローしているユーザーの取得を行います。
1つ目の処理でfollow
から一致するレコードを取り出します
そしてそれを元に、user
モデルを取得します
自分をフォローしてくれるユーザー
has_many :reverse_follows, class_name: 'Follow', foreign_key: :follow_user_id, dependent: :destroy
-
reverse_follows
はメソッド名です。 -
reverse_follow
と勘違いされないように、class_name: 'Follow'
明示します。follow
モデルと明示です。 -
foreign_key: :follow_user_id
でuser
のid
と関連付けします。
次
has_many :follower_users, through: :reverse_follows, source: :follower_user
-
follower_users
はメソッド名 -
reverse_follows
を経由する。 -
follower_user
これと一致するuser
モデルの取得、follow
モデルに従う
終わりに
laravelでも同じようなことをやっていましたが、しっかり仕組みを理解できていませんでした。
かなり勉強になりました。ありがとう