0

在保存一系列子模型时,我需要将更新的参数传递回父模型。
例如,如果通过一个项目保存一堆员工到每个任务,我需要让项目知道它的一些任务的标题发生了变化,那么我需要收集所有发生变化的标题并在 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
4

1 回答 1

0

听起来您需要使用此处描述的 after_save 方法http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

于 2013-03-21T22:35:09.567 回答