如何通过关联在has_many中使用回调? [英] Howto use callbacks in a has_many through association?
问题描述
我有一个通过has_many通过项目模型关联的任务模型,需要通过关联操作删除/插入之前的数据。
I have a Task model associated to a Project model via has_many through and need to manipulate the data before delete/insert via the association.
由于自动删除连接模型是直接的,没有销毁回调被触发。我不能使用回调这个。
Since "Automatic deletion of join models is direct, no destroy callbacks are triggered." i can not use callbacks for this.
在任务中,我需要所有的project_ids计算保存任务后的项目的值。
我如何禁用删除或更改删除通过关联破坏has_many?
这个问题的最佳实践是什么?
In Task i need all project_ids to calculate a value for Project after Task is saved. How can i disable delete or change delete to destroy on has_many through association? What is best practise for this problem?
class Task
has_many :project_tasks
has_many :projects, :through => :project_tasks
class ProjectTask
belongs_to :project
belongs_to :task
class Project
has_many :project_tasks
has_many :tasks, :through => :project_tasks
推荐答案
似乎我必须使用关联回调 before_add
, after_add
, before_remove
或 after_remove
Seems like i have to use associations callbacks before_add
, after_add
, before_remove
or after_remove
class Task
has_many :project_tasks
has_many :projects, :through => :project_tasks,
:before_remove => :my_before_remove,
:after_remove => :my_after_remove
protected
def my_before_remove(obj)
...
end
def my_after_remove(obj)
...
end
end
这篇关于如何通过关联在has_many中使用回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!