Rails应用中Referral自关联模型配置问题求助
Rails推荐系统模型关联正确配置方案
首先修正你的Referral模型,原代码中belongs_to :user是错误的,因为你的关联字段是godfather_id和godson_id,需要明确关联到User模型的对应角色:
class Referral < ApplicationRecord # 关联推荐人(godfather) belongs_to :godfather, class_name: 'User' # 关联被推荐人(godson) belongs_to :godson, class_name: 'User' # 可按需添加状态枚举,比如: # enum state: { active: 'active', pending: 'pending', rejected: 'rejected' } end
接下来修正User模型的关联配置,实现user.godsons和user.godfather的正确调用:
class User < ApplicationRecord # 1. 当前用户作为推荐人,拥有多个推荐关系 has_many :referrals, foreign_key: 'godfather_id', dependent: :destroy # 通过推荐关系获取所有被推荐人(godsons) has_many :godsons, through: :referrals, source: :godson # 2. 当前用户作为被推荐人,仅存在一个推荐关系 has_one :referral_as_godson, class_name: 'Referral', foreign_key: 'godson_id', dependent: :destroy # 通过该推荐关系获取自己的推荐人(godfather) has_one :godfather, through: :referral_as_godson, source: :godfather end
你的两种写法问题说明
- 写法一:lambda中的
where(godfather_id: id)无法正确绑定当前用户ID(关联lambda不能直接调用实例属性id),且has_many :godson是单数命名错误,同时未指定source导致Rails无法推断关联对象。 - 写法二:外键配置完全颠倒——
godson_relations的外键应设为godfather_id(表示用户作为推荐人的关系),godfather_relation的外键才是godson_id;另外has_one :godfather的through参数错误使用复数godfather_relations,且缺少source指定关联对象。
测试用法示例
# 创建推荐关系 godfather = User.create(name: "张三") godson = User.create(name: "李四") Referral.create(godfather: godfather, godson: godson, state: "active") # 获取张三的所有被推荐人 godfather.godsons # => [李四] # 获取李四的推荐人 godson.godfather # => 张三
内容的提问来源于stack exchange,提问作者rmfy
相关产品推荐
相关产品推荐

