1
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.

rails where の落とし穴

Last updated at Posted at 2018-12-05

はじめに

自分が引っかかってしまったので、将来見返すようにメモ。

whereメソッド

ご存知の通り、whereメソッドは条件に合うモデルを複数取得したい場合によく使われます。

今回起こったこと

今回の自分の事例では、条件に合うモデルを探してあったらif文実行、なかったらif文を飛ばすというものです。以下コードです。Userモデルにはhoge、hogehogeカラムがあるとします。

if users = User.where(hoge: hoge1)
   user = users.first
   if user.hogehoge < 10
            .
            .
            .
            .
   end
end

いざ実行してみるとundefined method 'hoge' for nil:NilClass.
なんでだーと思ったら単純な勘違いでした。

whereメソッドの働き

自分の勘違いで、whereメソッドが何も見つけなかったらnilを返すと思っていました。しかし実は中身が空っぽのActiveRecord::Relationオブジェクトを返すのでした。中身は空だけど、入れ物は入っているからnilじゃないよ的な...。だから最初のif文が実行されてしまいます。

題名のエラー処理

上記より中身が存在しているか存在してないかを条件に持って来れば良いので

users = User.where(hoge: hoge1)
if users.present?
   user = users.first
   if user.hogehoge < 10
            .
            .
            .
            .
   end
end

これで解決。

終わり

最近細かい勘違いのせいで時間が取られている気がする。この前だって学校のサーバーでつなげていることを忘れて、自分のwebアプリをいろいろいじろうとしたらエラーが出てかなり悩んだし。。
丁寧にやることって大事。

1
0
2

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
1
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?