具有多个连接的 ActiveRecord 查询无法识别关系

2024-02-14

我正在尝试编写一个 ActiveRecord 查询,使用以下查询返回注册特定课程的所有学生:

def self.students_enrolled_in(course_id)
    Student
        .joins(:enrollments)
        .joins(:sections)
        .joins(:courses)
        .where(sections: { course_id: course_id })
  end

Rails 控制台的结果是:

ActiveRecord::ConfigurationError:无法将“学生”加入名为“部分”的关联;也许你拼错了?

看来这个协会已经成立了。我究竟做错了什么?该查询实际上意味着所有join()陈述必须与学生相关,或者应该追踪关系链接?

教授展示页面:

<div class="col-md-8">
  <h2 class="card-title"><%= @professor.name %></h2>

    <% @courses_taught.each do |course| %>
        <div class="card mb-4 card-header">
          <img class="card-img-top" src="http://placehold.it/750x300" alt="Card image cap">
          <h3 class="card-text"><%= course.title %></h3>
        </div>
        <div class="card-body">
          <% course.sections.enrollments.students.each do |student| %>
              <p><% student.name %></p>
          <% end %>
        </div>
    <% end %>

</div>

models:

注册

class Enrollment < ApplicationRecord
  belongs_to :section
  belongs_to :student
end

Student:

class Student < ApplicationRecord
  has_many :enrollments
end

教授:

class Section < ApplicationRecord
  has_many :enrollments
  belongs_to :professor
  belongs_to :course

  validates_uniqueness_of :professor_id, scope: :course_id

  scope :by_professor_id, ->(prof_id) { where('professor_id = ?', prof_id) }
end

Course:

class Course < ApplicationRecord
  enum status: { planning: 0, offered: 1 }

  scope :offered, -> { where(status: 1) }
  scope :planning, -> { where(status: 0) }

  belongs_to :department
  has_many :sections
  has_many :professors, through: :sections

  validates :title, :number, :status, :description, presence: true
  validates :description, length: { in: 10..500 }
  validates :title, :number, uniqueness: { case_sensitive: false }

  def self.search(term)
    if term
      where('title LIKE ?', "%#{term}%").order('title DESC')
    else
      order('title ASC')
    end
  end

  def self.taught_by(professor_id)
    Course
        .joins(:sections)
        .joins(:professors)
        .where(sections: { professor_id: professor_id })
        .select('distinct courses.*')
  end

end

Schema:

ActiveRecord::Schema.define(version: 20171013201907) do

  create_table "courses", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.string "number"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "status", default: 0
    t.integer "department_id"
    t.index ["department_id"], name: "index_courses_on_department_id"
  end

  create_table "departments", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.text "main_image"
    t.text "thumb_image"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "enrollments", force: :cascade do |t|
    t.integer "section_id"
    t.integer "student_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["section_id"], name: "index_enrollments_on_section_id"
    t.index ["student_id"], name: "index_enrollments_on_student_id"
  end

  create_table "professors", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "status", default: 0
    t.integer "department_id"
    t.text "bio"
    t.index ["department_id"], name: "index_professors_on_department_id"
  end

  create_table "sections", force: :cascade do |t|
    t.integer "number"
    t.integer "max_enrollment"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "professor_id"
    t.integer "course_id"
    t.string "room"
    t.index ["course_id"], name: "index_sections_on_course_id"
    t.index ["professor_id", "course_id"], name: "index_sections_on_professor_id_and_course_id", unique: true
    t.index ["professor_id"], name: "index_sections_on_professor_id"
  end

  create_table "students", force: :cascade do |t|
    t.string "name"
    t.decimal "gpa"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "name"
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "roles"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

另一种方法是向您的Student model:

class Student < ApplicationRecord
  has_many :enrollments
  has_many :sections, through: :enrollments
  has_many :courses, through: :sections

  scope :enrolled_in_course, -> (course) { joins(:sections).where(course_id: course.id)
end

然后,您可以找到就读于某个课程的所有学生course with:

Student.enrolled_in_course(course)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有多个连接的 ActiveRecord 查询无法识别关系 的相关文章

随机推荐

  • Buffer.BlockCopy 与不安全的 byte* 指针复制

    复制字节块时哪个性能更好 Buffer BlockCopy非常优化 它基本上是原始内存副本的包装器 所以它应该非常快 并且避免弄乱指针和unsafe代码 它应该是默认的 你当然可以用各种方式来衡量
  • HList 选项的幂集

    我正在玩 Shapeless 我正在尝试计算 某种 powerset https en wikipedia org wiki Power set of an HList of Options 基本上 我想解释一下HList作为一个集合 在这
  • Angular2 /错误:找不到集合

    我对 Angular2 很陌生 正在尝试构建一个 Todo 应用程序 这是我的文件结构 My todo service ts代码 里面shared folder import Injectable from angular core imp
  • tkinter 中的“权重”有什么作用?

    我一直在搜索不同的网站 试图找出权重在 tkinter 中的作用 我从那里得到这个TkDocs http www tkdocs com tutorial grid html 每列和行都有一个与之关联的 权重 网格选项 该选项告诉它如果母版中
  • 使用 UNION 将数据拉入网格

    我的网站上有一个数据网格 我从两个表中提取公司信息 我正在创建一个表单来根据 3 个过滤器 类别 州 城市 对这些结果进行排序 这是我最初将数据加载到网格中的查询 我希望它填充我的所有表数据 直到用户决定过滤它 这就是为什么我使用 UNIO
  • 使用 gradle 'java-library' 时无法引用库中的类

    升级到 Android Studio 3 0 后我还使用新的 android gradle 插件com android tools build gradle 3 0 0 alpha1我想用java 库 https docs gradle o
  • Mac apache localhost 给出 403 Forbidden

    我正在尝试在我的新 mac OSX 10 9 上设置本地环境 我知道它已经安装了apache 所以我一直在使用它 无论我如何设置 httpd vhosts conf hosts httpd conf 文件 在浏览器上访问 localhost
  • VS Code 接受有关输入不起作用的建议

    Normally pressing enter accepts a suggestion on intellisense but when I press enter it does not accept the suggestion an
  • 是否可以在 socket.io 中使用 UDP?

    我正在开发一款游戏 听说 UDP 更适合实时游戏 我知道 socket io 使用 TCP 并且想知道是否有某种方法可以将其切换到 UDP 我尝试查找它 但只找到了 2012 年左右的帖子 其中说 UDP 仅在浏览器中处于实验阶段 从标准浏
  • xvfb(带有 Mesa 19.2)与 Vulkan 兼容吗?

    我正在尝试在无头 Ubuntu 19 10 虚拟机上运行基于 Vulkan 的图形应用程序 通过xvfb https en wikipedia org wiki Xvfb 从裸露的 Ubuntu 19 10 映像开始 使用创建lxc htt
  • 摆脱 NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE?

    我越来越NP NULL ON SOME PATH FROM RETURN VALUE在这个片段中 final Integer id Ints tryParse idString FailReason NO SUCH THING checkC
  • 协方差胜过具体类型?

    老实说 我问过 这个问题的一部分 here https stackoverflow com questions 9335278 covariance in different fw causes code break但现在我有一个不同的相关
  • 避免在数据表中呈现“表中没有可用数据”

    我正在使用 JQuery 数据表 当表格呈现时 它显示为 表格中没有可用数据 一段时间后表格开始显示数据 并且 没有可用数据 消失 我不希望出现 没有可用数据 相反 如果出现 正在加载 或 请稍候 之类的内容 那就太好了 或者没有任何东西可
  • 当鼠标离开JQuery时停止.hover动画

    我有类似的东西 test hover function this animate function this animate 但如果用户的鼠标在动画结束之前离开 动画将继续 如果我快速重复地快速悬停和取消悬停元素 则动画会在鼠标离开元素后重
  • 从 3 个点检索正角或负角

    我正在围绕二维空间中的中心点旋转点 这些点是中心点 旧鼠标位置和新鼠标位置 我的旋转功能运行良好 我可以完美地计算角度 但如果用户沿应解释为逆时针方向移动鼠标 我想计算负角度 例如 如果您位于 小于 中心点的 y 值之上 小于 则向右 正
  • window、window.top 和 window.parent 之间有什么区别?

    我刚刚注意到top window and parent变量给了我相同的值 我正在 gmail 收件箱页面对此进行测试 有人知道这三个值有什么区别吗 如果您在框架内 window指当前帧 parent指的是当前框架的父级 top指最外层框架
  • 元音子序列

    我在准备面试时在网站上发现了这个问题 字符串的神奇子序列S是一个子序列S那 按顺序包含所有五个元音 查找字符串的最大神奇子序列的长度S 例如 如果S aeeiooua then aeiou and aeeioou是神奇的子序列 但aeio
  • 将 TIMESTAMP 列更新为可为空

    我有一个表存在于两个数据库中 在一个数据库中有一个表 其中有一列称为ROW VERSION这是类型TIMESTAMP NOT NULL 在第二个数据库中 同一个表具有相同类型的列TIMESTAMP但它是类型TIMESTAMP NULL 我想
  • 活动图 定时事件

    我正在尝试建模以下内容 填写提交表单时 系统每 5 分钟自动保存一次用户进度 这是我尝试过的 但我认为这是不正确的 就我而言 仅在 填写提交 活动完成后才会询问条件 另外 我不想表明用户正在再次开始 填写提交 活动 您将使用由虚线框表示的可
  • 具有多个连接的 ActiveRecord 查询无法识别关系

    我正在尝试编写一个 ActiveRecord 查询 使用以下查询返回注册特定课程的所有学生 def self students enrolled in course id Student joins enrollments joins se