开发者

Checking a related relationship once the instance is created

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

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜