문제

    class Annex
      has_and_belongs_to_many: :documents
    end

    class Document
      has_and_belongs_to_many: :annexes
    end 

I want to implement this behavior: if the annex is associated to at least one document, it shouldn't be destroyed.

Is there a easy rails way of doing this or will I have to make a work around this?

Will I have to use a before_destroy method or something like that?

도움이 되었습니까?

해결책

Do something like this:

class Annex < ActiveRecord::Base
  has_and_belongs_to_many :documents
  before_destroy { raise "Can't destroy Annex, because it's still associated to 1 or more documents" if documents.any? }
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top