given
[ahoward@localhost rest]$ cat schema.sql
create table people (
id serial,
first_name text,
last_name text
);
create table students (
id serial,
person_id int
);
create table teachers (
id serial,
person_id int
);
create table courses (
id serial,
subject text
);
create table courses_students (
id serial,
course_id int,
student_id int
);
create table courses_teachers (
id serial,
course_id int,
teacher_id int
);
[ahoward@localhost rest]$ cat app/models/{p,s,t,c}*
class Person < ActiveRecord::Base
has_one :student
has_one :teacher
end
class Student < ActiveRecord::Base
belongs_to :person
has_and_belongs_to_many :courses
end
class Teacher < ActiveRecord::Base
belongs_to :person
has_and_belongs_to_many :courses
end
class Course < ActiveRecord::Base
has_and_belongs_to_many :teachers
has_and_belongs_to_many :students
end
class CourseStudent < ActiveRecord::Base
set_table_name “courses_students”
belongs_to :course
belongs_to :student
end
class CourseTeacher < ActiveRecord::Base
set_table_name “courses_teachers”
belongs_to :course
belongs_to :teacher
end
and wanting to get a list of a particular teacher’s students. is there
any
more elegant what than this?
[ahoward@localhost rest]$ ./script/console
Loading development environment.
teacher = Teacher.find 1
=> #<Teacher:0xb782d028 @attributes={“id”=>“1”, “person_id”=>“1”}>students = teacher.courses.inject([]){|list, c| list.push
*c.students}
=> [#<Student:0xb7825314 @attributes={“student_id”=>“1”, “id”=>“1”,
“course_id”=>“1”, “person_id”=>“1”}>, #<Student:0xb78252d8
@attributes={“student_id”=>“2”, “id”=>“2”, “course_id”=>“1”,
“person_id”=>“2”}>]
i know i could contruct a single sql statement to do this - but can that
be
done in rails with one statement? this approach does one for each
course.
kind regards.