arsro.net

[Rails] Active Record で where A and ( B or C )


毎回どうするか忘れてしまうのでメモ。

Post.where(A).where(B).or(Post.where(C))

// 実行結果
// select * from posts where A and B or C

これだと「and」が優先されて実行されるため( A and B ) or Cということになる。

しかし、本当はA and ( B or C )という条件のSQLを実行したい🥺


結論

Post.where(B).or(Post.where(C)).where(A)

// 実行結果
// select * from posts where ( B or C ) and A

ActiveRecordでは、評価の優先順をチェーンメソッドの並び順で表現するらしいのでこれでOK。

参考

#tech

最近のポスト