2
3

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で頻発する NoMethodError for nil をかっこよく避けよう!

Last updated at Posted at 2018-07-13

##みなさんよくレコードいじってると、nilに悩まされるとおもいます。
こんな感じ

puts Order.first.client.address.street
# => NoMethodError: undefined method `client' for nil:NilClass

そうすると真っ先に思いつく解決策はこれ

うーん汚いですねwww
No way!

order = Order.first
if order && order.client && order.client.address
  puts order.client.address.street
end
# => nil

##そこで次に思いつくのはRailsのactivesupportを使った方法

order = Order.first
puts order.try(:client).try(:address).try(:street)
# => nil

まぁあまぁあイケてますね〜

##ただruby2.3以降ならもっといけてる方法が!

order = Order.first
puts order&.client&.address&.street
# => nil

これです、swift,c#にもあるsafe navigation operatorという機能を使えばいいのです!

##この記事はmediumのある記事をサクッと翻訳、要約したものです。本家には#digの紹介もあるのでぜひご覧ください!

##参照
mediumのページ

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?