使用多对多和联接的 Rails 作用域



我正在尝试编写一个 rails 查询,该查询返回特定教授教授的课程列表。 我尝试使用的查询是:

def self.taught_by(professor_id)
    Course
        .joins(:sections)
        .joins(:professors)
        .where(['profesor_id = ?', professor_id]).select('distinct courses.*')
  end

SQLite3::SQLException: no 这样的列: profesor_id: S...

如何使用引用不同表的 where 子句? professor_id位于"节"表中。

使用以下.rb文件:

教授:

class Professor < ApplicationRecord
enum status: { sabbatical: 0, available: 1 }
has_many :sections
has_many :courses, :through => :sections
belongs_to :department
validates :name, presence: true
validates :name, length: { in: 4..32 }
validates :name, uniqueness: { case_sensitive: false }
def self.search(term)
  if term
    where('name LIKE ?', "%#{term}%").order('name DESC')
  else
    order('name DESC')
  end
end
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

课程:

    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(['profesor_id = ?', professor_id]).select('distinct courses.*')
end
end

任何帮助将不胜感激。我有点被困在这件事上。

可以使用表名作为哈希中的键来指定列存在于哪个表中。

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

看起来您的where可能有错别字... profesor_id = ?,这是对的吗?

最新更新