0

in transactions, sometimes customers do not have service_id because they did not add additional services to cart. problem is, transactions index page returns undefined method 'name' for nil:NilClass on line

<%= transaction.service.name %>

Is there any way better than

<%= transaction.service.present? ? transaction.service.name : nil %>

I found this NULL OBJECT PATTERN article. didn't quite understand how it applies on my scenario.

Hadi Farnoud
  • 131
  • 1
  • 15
  • You tagged the question with `null-object-pattern`? Do you actually know this pattern (because it's a way to go here) or you just picked that tag because it starts with `null-object`? – Sergio Tulentsev Jan 28 '13 at 04:45

1 Answers1

2

Or you can do this:

transaction.service.try(:name)

If service is not nil, it will return its name. Or it will return nil otherwise.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • by Null Object Pattern I meant http://robots.thoughtbot.com/post/12179019201/design-patterns-in-the-wild-null-object – Hadi Farnoud Jan 28 '13 at 05:59
  • I didn't quite understood how that applies in my case. hence asking it here. – Hadi Farnoud Jan 28 '13 at 06:00
  • 1
    Yeah, that's the pattern. You can also watch this: [Null Objects and Falsiness](http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/). But I'd go with `try` method in this case. – Sergio Tulentsev Jan 28 '13 at 06:07