2012-05-15 30 views
20

Tôi có một mô hình Nhiệm vụ được liên kết với mô hình Dự án qua has_many và cần thao tác dữ liệu trước khi xóa/chèn thông qua liên kết.Làm cách nào để sử dụng gọi lại trong liên kết has_many?

Vì "Automatic deletion of join models is direct, no destroy callbacks are triggered." tôi không thể sử dụng gọi lại cho việc này.

Trong công việc tôi cần tất cả các project_ids để tính giá trị cho dự án sau khi tác vụ được lưu. Làm thế nào tôi có thể vô hiệu hóa xóa hoặc thay đổi xóa để tiêu diệt has_many thông qua liên kết? Thực tiễn tốt nhất cho vấn đề này là gì?

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 

Trả lời

45

Có vẻ như tôi phải sử dụng associations callbacksbefore_add, after_add, before_remove hoặc 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 
1

Đây là những gì tôi đã làm

trong mô hình:

class Body < ActiveRecord::Base 
    has_many :hands, dependent: destroy 
    has_many :fingers, through: :hands, after_remove: :touch_self 
end 

trong tôi Thư mục Lib:

module ActiveRecord 
    class Base 
    private 
    def touch_self(obj) 
     obj.touch && self.touch 
    end 
    end 
end 
Các vấn đề liên quan