TJ Sherrill
TJ Sherrill

Reputation: 2645

Rails how to know if a has_one/belongs_to relationship exists

I have a 'User' (devise), and a 'Location'. A user has_one location while a location belongs_to user. I have an instance variable in my controller that only should exist if two conditions are true.

if user_signed_in? && !current_user.location.empty?

But the error returns:

undefined method 'empty?' for nil:NilClass

Which is right because the current_user doesn't have a location. I'm searching on Google about this for 2 hours. I'm not sure what I'm missing here.

Upvotes: 1

Views: 2120

Answers (1)

Xerif917
Xerif917

Reputation: 132

It's giving you the undefined method error because current_user.location is not an array. empty? can only be used on an array. Try using nil? instead.

Upvotes: 5

Related Questions