アクティブなレコードのクエリ
概要
早速本題に入ります。
私はこれら 2 つのモデルを持っています:
フォローされたモデルには、
ユーザーモデルは次のようになります。
has_many :followeds, foreign_key: :followed_id, dependent: :destroy
フォローされたモデルは次のようになります
belongs_to :user
私が達成したいのはこれです: current_user (ログインしているユーザー) のフォロワーを取得したいです。
何をすべきかについてはいくつか考えがありますが、それは次のようなものです。
1 - ユーザーテーブルとフォローテーブルを結合します
2 - users.id = Followings.user_id (current_user をフォローするユーザー) のユーザーを選択します。
3 - and (条件) follows.followed_id = current_user.id (フォローされているユーザーは、ログインしている current_user です)
役立つかどうかはわかりませんが、次のクエリは、ユーザーがフォローしているユーザーを取得するために (スタック オーバーフロー ユーザーの親切な助けを借りて) 使用することに成功したものです。
@users = User.joins(:followeds).where(followeds: {user_id: current_user.id})
それに基づいて、クエリは次のようになると思います
@users = User.joins(:followeds).where(followeds: {followed_id: current_user.id})
次に、users.id = Followings.user_id を選択するためのクエリ
解決策
あなたの関連性が明確に理解できれば
User.where(id: Followed.select(:user_id).where(followed_id: current_user.id))
このような SQL が生成されます
SELECT * FROM users
WHERE id IN (
SELECT user_id FROM followeds
WHERE followed_id = <current_user_id>
);
:source および :through オプションを使用して User モデルに関連付けを追加することもできます
has_many :followers, through: :followeds, source: :user
そして、ただそれだけではなく
current_user.followers
これにより、次のようなクエリが生成されます
SELECT * FROM users
INNER JOIN followeds ON users.id = followeds.user_id
WHERE followeds.followed_id = <current_user_id>;