4
8

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.

activesupport のtryメソッドは便利!

Posted at

よくあるviewのエラーで関連テーブルのレコードが削除されちゃって

@hoge.user.name

の箇所で例外吐くので

NoMethodError: undefined method name' for nil:NilClass`

なんてなったりします。

今までは

@hoge.user.name unless @hoge.user.blank?

とか

@hoge.user.blank? ? "不明" : @hoge.user.name

とかで対応していたが、最近tryメソッドの存在を知った。
tryを使うと以下のように書ける

@hoge.user.try(:name)

とか

@hoge.user.try(:name) || "不明"

なんて書けて便利!

4
8
1

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
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?