开发者

Checking a related relationship once the instance is created

开发者 https://www.devze.com 2022-12-21 09:16 出处:网络
I have a schema where: Students has_and_belongs_to_many :courses has_many :grades, :dependent => :destroy

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

精彩评论

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