2016-06-08 5 views
1

를 작동하지 않습니다 파괴 나는 다음과 같은 클래스가 :레일 5 의존 :

update_attribute(:deleted_at, Time.now) 
: 여기

class Product < ApplicationRecord 
    belongs_to :product_category 

    def destroy 
    puts "Product Destroy!" 
    end 

end 

class ProductCategory < ApplicationRecord 
    has_many :products, dependent: :destroy 

    def destroy 
    puts "Category Destroy!" 
    end 
end 

가, 나는 결국이 작업을 수행하려는 방법을 파괴 오버라이드 (override)하는 것을 시도하고있다 나는 레일 콘솔에 다음 문을 실행하면

는 : ProductCategory.destroy_all를 나는 다음과 같은 출력을

Category Destroy! 
Category Destroy! 
Category Destroy! 

주를 얻을 : I 시간 3 개의 카테고리가 있으며 각 카테고리에는 하나 이상의 제품이 있습니다. 제품 배열을 반환하는 ProductCategory.find(1).products으로 확인할 수 있습니다. Rails 5에서 구현이 변경되었다는 소식을 들었습니다. 어떻게 작동시킬 수 있습니까?

편집

나는 결국, 소프트에 범주와 한 번에 모든 관련 제품을 삭제한다 원하는 것은. 이것이 가능한가? 아니면 파괴 전 콜백의 모든 Product 객체를 반복 할 수 있습니까? 당신은 당신의 파괴 방법에서 슈퍼를 호출해야

+0

파괴 방법을 모두 제거하고 다시 시도하십시오. –

+0

그것은 당신이 active_model 파괴 방법을 능가하고 있고 파괴에서 "super"라고 불러야한다고 생각합니까? –

+0

저는 ActiveRecord 메서드를 덮어 쓰는 것을 권장하지 않습니다. 기존의 것을 덮어 쓰는 대신에'update_as_destroyed'와'update_as_destroyed_all'처럼 자신 만의 것을 만드십시오. – Kkulikovskis

답변

1

그래서 이것은 내가 결국 그것을 어떻게입니다 우리를 위해.

0

(나를 위해 마지막 옵션) :

def destroy 
    super 
    puts "Category destroy" 
end 

그러나 나는 확실히 당신이 활성 모델 메소드를 오버라이드 (override)하는 것을 제안하지 않을 것입니다.

class Product < ApplicationRecord 
    belongs_to :product_category 

    def destroy 
    run_callbacks :destroy do 
     update_attribute(:deleted_at, Time.now) 
     # return true to escape exception being raised for rollback 
     true 
    end 
    end 

end 

class ProductCategory < ApplicationRecord 
    has_many :products, dependent: :destroy 

    def destroy 
    # run all callback around the destory method 
    run_callbacks :destroy do 
     update_attribute(:deleted_at, Time.now) 
     # return true to escape exception being raised for rollback 
     true 
    end 
    end 
end 

내가로부터 진정한 반환하고는 조금 위험 update_attribute 만드는가 파괴하지만 난뿐만 아니라와 ApplicationController 수준에서 예외를 잡기하고, 잘 작동합니다

+0

그의 질문에 따르면 기록이 여전히 파괴 될 수 있기 때문에 작동하지 않을 것입니다. 그는 그걸 원하지 않습니다. – Kkulikovskis

+0

예, 그게 그가하고 싶어하는 것이지만, 제 대답은 그의 질문에 대한 것입니다. 그 이유는 : 파괴는 효과가 없습니다. 그는 자신이 원하는 업데이트를 구현하는 방법을 묻지 않습니다. –

+0

예, 질문을 수정했습니다. –