LoginSignup
0
0

More than 3 years have passed since last update.

joinsで結合したモデルのscopeを使ってデータを取得する方法

Last updated at Posted at 2020-01-24

inner joinかつ別モデルのscopeを利用してそのモデルの状態を条件にデータを取得したい。
例えば、「紐づくuserのstatusがtrueであるtweet」を取得したいときは以下のように書ける。

Tweet.joins(:user).merge(User.available)

user.rb

class User < ApplicationRecord
  has_many :tweets
  scope :available, -> {
    where(status: true)
  }
end

tweet.rb

class Tweet < ApplicationRecord
  belongs_to :user
end
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