我有一个简单的 has_one 关系
class User < ApplicationRecord
has_one :detail
has_many :courses
end
class Detail < ApplicationRecord
belongs_to :user
end
我需要检查用户是否有详细信息。既然我能做到User.first.courses.exists?
令人惊讶的是User.first.detail.exists?
不起作用。我可以!User.first.detail.nil?
但我只需要检查用户详细信息是否存在,而不加载它的非常庞大的详细模型。
在不检索整个关联模型的情况下检查 has_one 关联是否存在的好方法是什么?
Detail.where(user_id: User.first.id).exists?
这不会分配Detail
如果您只想知道用户是否有详细信息,则对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)