You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails关联问题:调用user.tutors.favorites提示方法未定义

问题修正方案

先梳理现有代码里的核心问题:

  • Event模型中has_many :registrations的外键配置错误,Registration表用event_id关联Event,不是program_id
  • User模型里的favorites关联逻辑偏离需求:你要获取的是收藏的导师,但当前关联指向Event,且through关联的目标错误
  • 执行user.tutors.favorites报错,是因为tutors返回的是User集合对象,这个集合没有定义favorites方法,favorites是单个User实例的关联,无法直接在集合上调用

修正后的模型代码

user.rb

class User < ApplicationRecord
  enum kind: { student: 0, tutor: 1, tutor_student: 2 }

  has_many :registrations
  # 获取所有关联的导师
  has_many :tutors, through: :registrations, source: :tutor
  # 获取收藏的导师:通过registrations筛选favorite为true的记录,关联到tutor
  has_many :favorite_tutors, -> { where(registrations: { favorite: true }) }, 
           through: :registrations, 
           source: :tutor,
           class_name: 'User'
end

Event.rb

class Event < ApplicationRecord
  # 修正外键配置,默认会使用event_id关联Registration
  has_many :registrations
  has_many :users, through: :registrations
  # 关联活动对应的导师
  has_many :tutors, through: :registrations, source: :tutor
end

registration.rb

class Registration < ApplicationRecord
  belongs_to :user
  belongs_to :tutor, class_name: 'User'
  belongs_to :event
end

使用方式

现在可以直接通过以下代码获取用户收藏的导师:

user.favorite_tutors

如果需要筛选特定活动下的收藏导师,可以直接查询:

# 获取用户在指定活动中收藏的导师
user.registrations.where(event_id: 1, favorite: true).map(&:tutor)

内容的提问来源于stack exchange,提问作者SkRoR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:05:10