【问题标题】:get record from many to many relationship从多对多关系中获取记录
【发布时间】:2019-07-17 13:49:22
【问题描述】:

我正在处理一个旧的 Rails 项目。我通过名为students_courses 的桥接模型在Student 和Course 之间建立了多对多关系。

Student类:

class Student < ActiveRecord::Base
  has_and_belongs_to_many :courses, :class_name => 'Course', :join_table => 'students_courses'
end

Course类:

class Course < ActiveRecord::Base

end

StudentCourse类:

class StudentCourse < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

Student 模型中有一个firstname 属性。我想找到拥有firstname“John”并学习“foo”课程的学生。我怎样才能在 Rails 的 ruby​​ 中得到这个?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    只需将课程加入学生并进行查询

    Student.joins(:courses).where(firstname: 'John', courses: { name: 'foo' })
    

    您可以在rails guides阅读更多内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2018-02-18
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多