0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ActiveRecord の where in 句 の 空配列

Posted at

通常の where in 句

こういう書き方をすると思います。

select * from table_name where id in (1, 2, 3, 4, 5)

これをそのまま active_record で表現すると

TableName.where(id: [1, 2, 3, 4, 5])

ですよね。

in の中身が空だと

select * from table_name where id in ()

これは流石にエラーになりますよね?

active_record でこれをやると...

TableName.where(id: []) #=> []

お、エラーじゃなく空配列だ。

どうなってる?

to_sql で active_record は発行する sql を視認出来ますよね?
早速確認

TableName.where(id: []).to_sql #=> SELECT `table_name`.* FROM `table_name` WHERE 1=0

むむ!

WHERE 1=0

まさかの回避術

というか 空配列なら実行するなってツッコミどころもありますが、うっかり実行してもエラーにならない理屈はこういう事みたいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?