gpt4 book ai didi

ruby-on-rails - before_destroy 不是从 update_attributes 触发的

转载 作者:行者123 更新时间:2023-12-04 10:58:09 25 4
gpt4 key购买 nike

我有一个学生,他有很多类(class)。在 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

最佳答案

事实证明,此行为已记录在案,就在 上。 has_many 方法。来自 API 文档:

collection=objects Replaces the collections content by deleting and adding objects as appropriate. If the :through option is true callbacks in the join models are triggered except destroy callbacks, since deletion is direct.



我不确定“因为删除是直接的”是什么意思,但我们知道了。

关于ruby-on-rails - before_destroy 不是从 update_attributes 触发的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com