Don P
Don P

Reputation: 63567

Check whether an attribute of a model exists

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

Answers (3)

vee
vee

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

Marco Prins
Marco Prins

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

Matteo Melani
Matteo Melani

Reputation: 2726

if @user.computer && @user.computer.brand.present?

Upvotes: 0

Related Questions