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

Railsのリレーション

Posted at

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_iduseridと関連付けします。

has_many :follower_users, through: :reverse_follows, source: :follower_user
  • follower_usersはメソッド名
  • reverse_followsを経由する。
  • follower_userこれと一致するuserモデルの取得、followモデルに従う

終わりに

laravelでも同じようなことをやっていましたが、しっかり仕組みを理解できていませんでした。
かなり勉強になりました。ありがとう

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