2017-12-28 30 views
0

카메라를 파괴하기 전에 CameraVectors가 MonitoredPlace에 연결되었는지 확인해야합니다.왜 중첩 된 연결에서 중단을 throw하면 "레코드를 파괴하지 못했습니다"예외가 발생합니까?

카메라의 모델 때문에 나는이 중첩 된 필드로 전송됩니다 카메라를 업데이트하거나 파괴하려고 할 때마다 accepts_nested_attributes_for의

class Camera < ApplicationRecord 
    belongs_to :location 
    has_many :camera_vectors, inverse_of: :camera, dependent: :destroy 

    validates :description, :device_serial, :device_name, 
    :device_type, :device_api_url, :device_user, :device_password, 
    presence: true 

    accepts_nested_attributes_for :camera_vectors, allow_destroy: true 
end 

CameraVector의 모델

class CameraVector < ApplicationRecord 
    belongs_to :camera, inverse_of: :camera_vectors 
    belongs_to :monitored_place, optional: true 

    validates :description, presence: true 
    validates :position, numericality: { greater_than_or_equal_to: 0 }, presence: true 

    before_destroy :has_monitored_place? 

    private 

    def has_monitored_place? 
    if monitored_place.present? 
     errors.add(:base, "cannot delete") 
     throw :abort 
    end 
    end 
end 

MonitoredPlace의 모델

class MonitoredPlace < ApplicationRecord 
    belongs_to :location 
    belongs_to :place_type 
    has_many :camera_vectors 

    validates :place_name, presence: true 
    validates :place_type_id, uniqueness: { scope: :location_id }, presence: true 

    scope :enabled, -> { where.not(enabled_on: nil).where(disabled_on: nil) } 
end 

매개 변수

"camera_vectors_attributes"=>{"0"=>{"description"=>"A", "position"=>"1", "_destroy"=>"1", "id"=>"47"}} 

나는 CameraVector 모델에서 콜백 before_destroy를 작성했는데 유효성을 검사 할 수 있지만 유효성 검사가 발생하면 컨트롤러에 ActiveRecord :: RecordNotDestroyed가 발생합니다.

if @camera.destroy(camera_params) 
    redirect_to(action: :index, notice: t(".success")) 
else 
    render :index 
end 

답변

0

당신이 api documentation

액티브 :: 읽을 수는 액티브 :: 자료 # 파괴에 의해 제기

을 RecordNotDestroyed! #destroy를 호출하면 false가 반환됩니다.

그것은 메서드를 호출하고 false을 반환

before_destroy :has_monitored_place? 

의 결과입니다.

def has_monitored_place? 
if monitored_place.present? 
    errors.add(:base, "cannot delete") 
    throw :abort 
end 
end 

begin 
    complex_operation_that_internally_calls_destroy! 
rescue ActiveRecord::RecordNotDestroyed => invalid 
    puts invalid.record.errors 
end 

또는 판독 된 API에 기재된 것과 유사한 로직을 구현이 동작을 변경할

How do I 'validate' on destroy in rails