54
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecord の or は merge とセットで使え

Last updated at Posted at 2018-12-12

さて問題

ActiveRecordでこんなクエリ( where 句)を作るにはどうしたら良いでしょうか?

where A and (B or C or D) and (E or F)

答え

Model.where(A)
     .merge(Model.where(B).or(Model.where(C)).or(Model.where(D)))
     .merge(Model.where(E).or(Model.where(F)))

merge() を使うと、 or() の部分をグルーピングすることができます。

SQLの条件組み立ては and で条件を絞り込んでいくのが基本ですから、 or の部分はまとめて and でつないでいきましょう。

or() はどこでグルーピングがどこに入るのか予測不可能なことが多いですが、merge() と併用するとグルーピングを明示的に制御できるようになります。

54
40
1

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
54
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?