我需要在保存一系列子项时将更新的参数传递回父模型 例如,如果通过项目将一堆员工保存到每个任务中,我需要让项目知道其某些任务的标题已更改,然后我需要收集所有已更改的标题并在ProjectObserver中处理它们。这可能吗?
我意识到可能没有办法按照我正在尝试的方式完成这项工作。如果不是,我很高兴听到有关如何解决这个问题的建议。
以下是我尝试过但没有取得任何成功:
class Employee < ActiveRecord::Base
has_many :employee_tasks
has_many :tasks, :through => :employee_tasks
accepts_nested_attributes_For :employee_tasks
accepts_nested_attributes_For :tasks
end
class Project < ActiveRecord::Base
attr_accessor :changed_employees
has_many :tasks
end
class Task < ActiveRecord::Base
has_many :employee_tasks
has_many :employees, :through => :employee_tasks
belongs_to :project
accepts_nested_attributes_For :employee_tasks
end
class EmployeeTask < ActiveRecord::Base
#this is what I want to accomplish
before_save do
if self.employee_id_changed
self.task.project.changed_employees ||= []
self.task.project.changed_employees << self.employee_id_changed
end
end
belongs_to :task
belongs_to :employee
end
class ProjectObserver < ActiveRecord::Observer
observe :project
def after_save(project)
puts project.changed_employees
# should print out the changed attributes loaded from EmployeeTask
#send a single email with all the updated titles (not one email for each change)
end
end
答案 0 :(得分:0)
听起来你需要使用这里描述的after_save方法http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html