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 に答える