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?

More than 5 years have passed since last update.

find_byはRangeが扱えない

0
Last updated at Posted at 2017-03-09

RailsのActiveRecordsで、
Hogeテーブルっていうのがあって

id type name
1 1 aaa
2 6 bbb
3 9 pero
4 12 moga
5 40 ccc

みたいなデータが入っていたとする。

見つからないときにraiseしたかったので find_by! を使いたいというときに

hoge = Hoge.find_by!(type: 1..10, name: 'pero')

ってやると、
期待してるデータがあるはず(id: 3)なのに見つからなくてraiseしてしまう。

Hoge.find_by(type: 1..10)

これがnilを返してしまうためっぽい。

Arrayならいける

RangeをArrayにすれば解決

hoge = Hoge.find_by!(type: [*1..10], name: 'pero')

期待してるレコードを取得できた。

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?