LoginSignup
2
1

More than 5 years have passed since last update.

RailsでLEFT OUTER JOINとIN句を同時に使う方法

Last updated at Posted at 2017-08-21

実装方法

SQLのLEFT OUTER JOINONの条件にIN句を書ければいいのですが、Railsではそれが出来ないようでした。
Railsで同様のことをやるには、以下のようにWHEREIN句の条件にnilを追加します。

# ユーザ別の最新のUserLocationのidを取得
latest_user_location_ids = UserLocation.group(:user_id).maximum(:id).values
users = User.
  includes(:user_locations).
  # IN句の条件にnilを含めないと、inner joinと同じ結果になってしまう
  where(user_location: { id: latest_user_location_ids.push(nil) }

参考

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