本文介绍了如何通过关联在 has_many 中使用回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 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_addafter_addbefore_removeafter_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 中使用回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:28