2011-01-29 1 views
5

레일 2.3.8. 3 가지 모델, 사용자, 소스 및 서브 스크립 션이 있습니다.해당 객체를 자동으로 삭제하는 조인 모델의 일부인 객체에 대해 destroy 콜백을 트리거하려면 어떻게합니까?

User attr_accessible :source_ids 
      has_many :subscriptions 
      has_many :sources, :through => :subscriptions 

Source  has_many :subscriptions 

Subscription belongs_to :user 
      belongs_to :source 

사용자가 소스에 대한 구독을 편집 할 수있는 인터페이스가 있습니다. 이 클래스는 source_ids를 수집하고 컬렉션을 기반으로 Subscription을 만들거나 삭제합니다. 내가 가지고있는 문제는 다음과 같습니다.

"조인 모델의 자동 삭제는 직접적이며 파괴 콜백은 발생하지 않습니다."

구독이 삭제되지 않고 삭제됩니다. 구독이 자동으로 결합 모델로 인해 삭제 될 때이 콜백을 트리거 할 수있는 방법

before_destroy do |subscription| 
    [Some irrelevant object not to be mentioned].destroy 
end 

내 질문은 : 나는 트리거되지 않습니다 구독 모델에 콜백을 가지고? rdoc에서

답변

5

HMT collection_singular_ids= deletion of join models is direct, no destroy callbacks are triggered

변경에 회신이 줄을 회신과 관련 있다면 그들은 :dependent => :destroy과 관련된하는 경우 파괴, 삭제 추가 될 것입니다 :

has_many :users, :through => :memberships, :after_remove => :your_custom_method 

그리고 사용자 모델에서 protected your_custom_method를 정의하십시오. 이 방법으로 사용자가 일부 Source에 대한 Subscription을 제거하면이 메서드가 호출됩니다.

행운을 빈다.

2
@user.subscriptions.delete 
has_many :subscriptions, :dependent => :destroy # <- setting this on the association will destroy the related subscriptions 
has_many :subscriptions, :dependent => :delete_all # <- setting this on the association will delete the related subscriptions 

:

collection.delete는 (객체, ...)
NULL 자신의 외래 키를 설정하여 컬렉션에서 하나 이상의 개체를 제거합니다. 이에

has_many :users, :through => :memberships 

: 객체는이 :dependent => :delete_all

관련 문제