Rails如何知道是否存在has_one/belongs_to关系

TJ *_*ill 1 ruby-on-rails has-one belongs-to model-associations

我有'用户'(设计)和'位置'.has_one位置belongs_to用户时的用户位置.我的控制器中有一个实例变量,只有在两个条件为真时才存在.

if user_signed_in? && !current_user.location.empty?
Run Code Online (Sandbox Code Playgroud)

但错误返回:

undefined method 'empty?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

哪个是正确的,因为current_user没有位置.我在谷歌上搜索了这个2个小时.我不确定我在这里缺少什么.

小智 5

它给你未定义的方法错误,因为current_user.location它不是一个数组.empty?只能在数组上使用.请尝试使用nil?.