LoginSignup
39
24

More than 5 years have passed since last update.

joinの際に任意のキー「同士」で結合したい時には、primary_keyとforeign_keyを使う

Last updated at Posted at 2015-10-08

下のようなテーブルとモデルがあったとする

articles
- id
- title
- content
article_plots
- id
- article_id
- plot_content
article_histories
- id
- article_id
- article_state
article.rb
  has_many :article_histories
  has_many :article_plots
article_plots.rb
  has_many :article_histories, foreign_key: :article_id, primary_key: :article_id
article_history.rb
  belongs_to :article

この時article_plotsとarticle_historyをAR経由でarticle_idを結合キーとしてjoinするには

article_plots.rb
  has_many :article_histories, foreign_key: :article_id, primary_key: :article_id

こういうふうに設定を足せば互いのarticle_idを見てjoinしてくれる

foreign_keyは自身の何を外部キーとするか、primary_keyは、相手の何を外部キーとするかを設定している。

下みたいなことをする必要はない...

joins('INNER JOIN article_histories ON article_histories.article_id = article_plots.article_id')
39
24
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
39
24