【发布时间】:2010-08-22 17:27:09
【问题描述】:
我有一个学生有很多课程。在 student#update 操作和表单中,我接受 course_ids 列表。当该列表更改时,我想调用某个函数。如果 update_attributes 创建了 course_student,我的代码确实会被调用,但如果 update_attributes 破坏 course_student,不会被调用。我可以让它触发,还是我必须自己检测更改?
# app/models/student.rb
class Student < ActiveRecord::Base
belongs_to :teacher
has_many :grades
has_many :course_students, :dependent => :destroy
has_many :courses, :through => :course_students
has_many :course_efforts, :through => :course_efforts
# Uncommenting this line has no effect:
#accepts_nested_attributes_for :course_students, :allow_destroy => true
#attr_accessible :first_name, :last_name, :email, :course_students_attributes
validates_presence_of :first_name, :last_name
...
end
# app/models/course_student.rb
class CourseStudent < ActiveRecord::Base
after_create :reseed_queues
before_destroy :reseed_queues
belongs_to :course
belongs_to :student
private
def reseed_queues
logger.debug "******** attempting to reseed queues"
self.course.course_efforts.each do |ce|
ce.reseed
end
end
end
# app/controllers/students_controller.rb
def update
params[:student][:course_ids] ||= []
respond_to do |format|
if @student.update_attributes(params[:student])
format.html { redirect_to(@student, :notice => 'Student was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @student.errors, :status => :unprocessable_entity }
end
end
end
【问题讨论】:
-
Rails 的哪个版本? Possibly Related Lighthouse discussion.
-
谢谢,安迪。这是 Rails 3,beta 4。也许是时候试试 RC 了?
-
我尝试将回调移动到 Student 模型,将 after_add 和 before_remove 回调放在 has_many course_students 关联中。同样的行为! after_add 触发,但 before_remove 不触发。
-
当前解决方法:我检测到当前课程列表中的更改。每门更改的课程都会重新播种。这是检测线(对于我未来的自己):@student.courses.collect{|c| c.id.to_s}.to_set ^ params[:student][:course_ids].to_set
标签: ruby-on-rails collections associations callback