course_section.rb 1.68 KB
Newer Older
Zac Wood's avatar
Zac Wood committed
1
2
# Contains logic belonging to the +CourseSection+ model.
class CourseSection < ApplicationRecord
3
  # Each +CourseSection+ belongs to a +Course+ and an +Instructor+.
Zac Wood's avatar
Zac Wood committed
4
  belongs_to :course
5
  belongs_to :instructor
Zac Wood's avatar
Zac Wood committed
6
7
8
9
10

  # Ensure all necessary fields are present.
  validates :name, presence: true
  validates :crn, presence: true
  validates :title, presence: true
11
  validates :course_id, presence: true
12

Zac Wood's avatar
Zac Wood committed
13
14
15
  def labs
    return nil unless section_type == "Lecture"

Zach Perkins's avatar
Zach Perkins committed
16
    lecture_number = name.split[name.split.length - 1]
Zac Wood's avatar
Zac Wood committed
17
    course.course_sections.select do |s|
Zach Perkins's avatar
Zach Perkins committed
18
      s.title.split[s.title.split.length - 1] == lecture_number
Zac Wood's avatar
Zac Wood committed
19
20
21
    end
  end

22
23
24
25
  # Select all course sections that have an instructor that matches the given name
  def self.with_instructor(name: "")
    joins(:instructor).where("instructors.name LIKE ?", "%#{name}%").select('course_sections.*, instructors.name as instructor_name')
  end
Zach Perkins's avatar
Zach Perkins committed
26

27
  def self.from_crn(base_query, crn)
Zach Perkins's avatar
Zach Perkins committed
28
    base_query.where("course_sections.crn = ?", crn)
29
  end
Zach Perkins's avatar
Zach Perkins committed
30

31
  def self.from_course_id(base_query, course_id)
Zach Perkins's avatar
Zach Perkins committed
32
    base_query.where("course_sections.course_id = ?", course_id)
33
  end
Zach Perkins's avatar
Zach Perkins committed
34

35
36
  # Select all revelevant course sections given the provided filters
  def self.fetch(filters)
37
    query = CourseSection.joins(:course).select("course_sections.*")
Zach Perkins's avatar
Zach Perkins committed
38

39
40
41
42
43
44
    filters.each do |filter, value|
      case filter
      when "crn"
        query = from_crn(query, value)
      when "course_id"
        query = from_course_id(query, value)
Zach Perkins's avatar
Zach Perkins committed
45
46
      when "course_number"
        query = Course.from_course_number(query, value)
47
48
      when "subject"
        query = Course.from_subject(query, value)
Zach Perkins's avatar
Zach Perkins committed
49
50
      when "title"
        query = Course.from_title(query, value)
51
52
      end
    end
Zach Perkins's avatar
Zach Perkins committed
53

54
    query
55
  end
Zac Wood's avatar
Zac Wood committed
56
end