
Untitled
By: a guest on
Jun 20th, 2012 | syntax:
None | size: 0.79 KB | hits: 9 | expires: Never
Rails or SQL to get through a few model associations
Timetable
has_many :enrollments
Enrollment
belongs_to :timetable
belongs_to :stream
has_one :course, :through => stream
#Stream & Timetable together are unique for an Enrollment
Stream
has_many :enrollments
belongs_to :course
Course
has_many :streams
Timetable.courses
Timetable
has_many :courses, :through => :enrollments, :source => :course
SELECT c.*
FROM courses c
LEFT JOIN streams s ON s.course_id = c.id
LEFT JOIN enrollments e ON e.stream_id = s.id
LEFT JOIN timetables t ON e.timetable_id = t.id
WHERE t.id = 5
Course.joins(:streams => {:enrollments => :timetables}).to_sql
Course.joins(:streams => {:enrollments => :timetables}).where(some condition on timetables)