I have a schema where:
Students
- has_and_belongs_to_many :courses
- has_many :grades, :dependent => :destroy
- has_many :assignments, :through => :grades
Courses
- has_many :assignments, :dependent => :destroy
- has_and_belongs_to_many :students
Assignments
- belongs_to :course
- has_many :grades, :dependent => :destroy
- has_many :students, :through => :grades
Grades
- belongs_to :student
- belongs_to开发者_JAVA技巧 :assignment
I would like to add functionality whereby if a grade is added and the student does not belong to the course that the grade's assignment belongs to, then this relationship is made. Any suggestions as to the best way to do this? The grades_courses table does not have it's own model, will this need to be made?
A friend has suggested using after_create, but I don't know how to pass the parameters to this.
How about an observer on grades? Something like this
class GradeObserver < ActiveRecord::Observer
def after_create(grade)
unless grade.assignment.course.students.include?(grade.student)
grade.assignment.course.students << grade.student
end
end
end
精彩评论