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
.
题
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?
解决方案
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
.
其他提示
if @user.computer && @user.computer.brand.present?
if @user.computer.present? && @user.computer.brand.present?
You can also use ! nil?
instead of present.
See this post - very useful