LoginSignup
0
0

More than 3 years have passed since last update.

ActiveRecordでwhere in句を書こうとして詰まったこと

Posted at

SQLで書くとわかるが、Railsでどのように書くか悩んだので、書いておく

知りたかったこと

SELECT * FROM Tables WHERE (name, task) not in ((yamada, "running"),(yamada, "swimming"));

いろいろ悩んだが上手くまとめられなかったので、サブクエリで解決しました〜!
配列で渡すと複数個渡せますし、このようにサブクエリにすると欲しい条件が作れるのかなと思います!

期待値通りのクエリが発行
Table.where.not(id: (Table.select(:id).where(name: yamada).where(task: ["running", "swimming"])))

当初の方針

最初の方針ではwhere句を複数繰り返すことで条件を絞れると思ってましたが、以下のように書いたら"yamada"さんの全てのtaskを弾いてしまいます。実際に発行されるSQLも下に記載しておきます。
ベン図を頭の中に描きながら書いていきました。

期待値と違うクエリが発行
Table.where.not(name: yamada).where.not(task: ["running", "swimming"])
期待値と違うクエリ
SELECT `tables`.* FROM `tables` WHERE `tables`.`deleted_at` IS NULL AND (`tables`.`name` != "yamada") AND (`tables`.`task` NOT IN ("running", "swimming"))

参考文献

Rails ガイド

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