문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top