Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to check if object can be destroyed if it has dependent restrict associations
class ActiveRecord::Base
def can_destroy?
self.class.reflect_on_all_associations.all? do |assoc|
assoc.options[:dependent] != :restrict || (assoc.macro == :has_one && self.send(assoc.name).nil?) || (assoc.macro == :has_many && self.send(assoc.name).empty?)
end
end
end
@kuboon

This comment has been minimized.

Copy link

commented Jul 19, 2013

nil? || empty? == blank?

assoc.options[:dependent] != :restrict || self.send(assoc.name).blank?

@barakargaman

This comment has been minimized.

Copy link

commented Dec 22, 2013

:restrict is deprecated. use instead:

  def can_destroy?
    self.class.reflect_on_all_associations.all? do |assoc|
      ( ([:restrict_with_error, :restrict_with_exception].exclude? assoc.options[:dependent]) ||
          (assoc.macro == :has_one && self.send(assoc.name).nil?) ||
          (assoc.macro == :has_many && self.send(assoc.name).empty?) )
    end
  end
@pierrea

This comment has been minimized.

Copy link

commented Feb 10, 2014

@barakarg Thanks for your edit! It works well. 👍

@gustaflindqvist

This comment has been minimized.

Copy link

commented Jun 19, 2014

@barakarg 👍

@timshingyu

This comment has been minimized.

Copy link

commented Oct 14, 2015

Still work in rails 4 👍

@jpvillaseca

This comment has been minimized.

Copy link

commented Jul 7, 2017

And in Rails 5 👍

@PragmaticEd

This comment has been minimized.

Copy link

commented Aug 13, 2018

I think this looks a bit cleaner..

class ActiveRecord::Base

  def can_destroy?
    self.class.reflect_on_all_associations.all? do |assoc|
      [
        %w(restrict_with_error restrict_with_exception).exclude?(assoc.options[:dependent].to_s),
        (assoc.macro == :has_one  && self.send(assoc.name).nil?),
        (assoc.macro == :has_many && self.send(assoc.name).empty?)
      ].include?(true)
    end
  end

end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.