Search code examples
ruby-on-railsmodel-associationsbelongs-tohas-one

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.


Solution

  • 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.