2013-03-21 76 views
0

我需要在保存一系列子級時將更新的參數傳遞迴父級模型。
例如,如果通過一個項目爲每個任務保存一堆僱員,我需要讓項目知道其中一些任務的標題已經更改,然後我需要收集所有更改的標題並在ProjectObserver。這可能嗎?rails - 如何將更改傳回父級模型

我意識到可能沒有辦法讓我按照我的方式工作。如果不是,我很樂意聽到關於我如何能夠解決這個問題的建議。

以下是我已經沒有任何成功的嘗試:

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 

回答