如何在User模型中创建has_one关联返回同类型活跃用户?
问题解决:has_one关联报错
column users.user_id does not exist 你在User模型里定义has_one :active_user时出错,原因是Rails的has_one关联默认会在关联表(这里是users表)中寻找user_id外键字段,用来关联当前模型实例和目标模型实例,但你的users表并没有这个字段,所以抛出错误。
根据你的实际需求,有几种解决方式:
1. 从其他模型关联到它的活跃用户
比如你有一个Account模型,要关联它的活跃用户,应该在Account模型里定义关联:
class Account < ActiveRecord::Base has_one :active_user, -> { where(status: :active) }, class_name: 'User' end
这时候Rails会自动查找users表的account_id外键,符合常规的关联逻辑。
2. 获取活跃用户集合/单个活跃用户
如果只是想在User模型中获取活跃用户,不需要用has_one关联,直接定义scope或类方法更合适:
class User < ActiveRecord::Base # 定义scope获取所有活跃用户 scope :active, -> { where(status: :active) } # 获取单个活跃用户(比如第一个) def self.active_user active.first end end
3. 用户与另一个活跃用户建立关联
如果确实需要用户模型关联到另一个活跃用户,你需要先给users表添加外键字段(比如active_associate_id),然后修改关联定义:
class User < ActiveRecord::Base has_one :active_user, class_name: 'User', foreign_key: 'active_associate_id' end
注意这里的外键要和你实际添加的字段名对应。
内容的提问来源于stack exchange,提问作者Petros Kalafatidis
相关产品推荐
相关产品推荐

