Question

    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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top