简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM