Reputation: 63567
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?
Upvotes: 0
Views: 78
Reputation: 38645
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
.
Upvotes: 2
Reputation: 7419
if @user.computer.present? && @user.computer.brand.present?
You can also use ! nil?
instead of present.
See this post - very useful
Upvotes: 0