LoginSignup
1
1

More than 1 year has passed since last update.

なんとActiveRecordはDB跨ぎでの関連付けが可能っぽい

Last updated at Posted at 2020-07-02

業務中に知って驚いたこと。休日に気が向いたら深堀するかも。

前提

  • User has_many Posts through UserPostsという関連付けをしたい。
  • Userテーブルは、PostsテーブルとUserPostsテーブルとは異なるDBのテーブル。

予想

User.rb
has_many :posts
has_many :read_posts, source: :posts, through: :user_posts

なんてasociationをモデル層に書いても流石にUser.read_postsは取ってこられないだろうと諦めの境地にいた。

しかしだ。。。

  • ActiveRecordがpreloadを使っているのなら、関連付け可能で取ってこれる
  • ActiveRecordがeagerloadを使っているのなら、関連付け不可能(生成されるクエリの中テーブルのでJOINを使っているから)

詳しいことは時間があったら調べてる予定

参考

memo. includesは、eager_loadとpreloadをよしなに使い分ける

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