LoginSignup
4
8

More than 5 years have passed since last update.

activesupport のtryメソッドは便利!

Posted at

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

@hoge.user.name

の箇所で例外吐くので

NoMethodError: undefined methodname' 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