Rails范围使用多对多和连接

时间:2017-10-18 22:37:21

标签: ruby-on-rails

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

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

SQLite3 :: SQLException:没有这样的列:profesor_id:S ...

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

包含以下.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

任何帮助都会非常感激。我有点坚持这个。

2 个答案:

答案 0 :(得分:2)

您可以使用表名作为哈希中的键来指定列所在的表。

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

答案 1 :(得分:1)

您的where ... profesor_id = ?看起来可能有拼写错误,这是正确的吗?