0

In Rails, I am getting an error when I try to evaluate whether the user has entered a brand for their computer:

if @user.computer.brand.empty?

NoMethodError (undefined method 'brand' for nil:NilClass):

If the user has not entered a computer, this will return an error that there is no method brand on nil class. What is the correct way to check that a user has both entered a computer and a brand for that computer?

Don P
  • 60,113
  • 114
  • 300
  • 432
  • simplest solution would be to just use `if @user.computer && @user.computer.brand.empty?` but a cleaner solution would be to use Null objects as specified in this article http://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object – jvnill Apr 02 '14 at 05:22

3 Answers3

2

Try with try:

@user.computer.try(:brand)

This will return nil if either computer or computer.brand is nil, or it will return the assigned brand.

vee
  • 38,255
  • 7
  • 74
  • 78
0
if @user.computer && @user.computer.brand.present?
Matteo Melani
  • 2,706
  • 2
  • 24
  • 30
0
if @user.computer.present? && @user.computer.brand.present? 

You can also use ! nil? instead of present.

See this post - very useful

Community
  • 1
  • 1
Marco Prins
  • 7,189
  • 11
  • 41
  • 76