开发者

Validate Before Destroy

I have three classes: School, Account, and Administratorship.

School

has_many :administatorships
has_many :administrators, :through => :administratorships

Account

has_many :administratorships

Administratorship

belongs_to :account
belongs_to :school

before_destroy :confirm_presence_o开发者_如何学Gof_alternate_administratorship_in_school

protected

def confirm_presence_of_alternate_administratorship_in_school
    unless school.administrators.count(["administratorships.account_id != #{id}"]) > 0
        errors.add_to_base "The school must have at least one administrator"
    end
end

Now, what I would like to happen is when I call destroy on an instance of Administratorship, for it to add an error to the model and prevent the destruction of the model. I have removed the unless statement to see if that was preventing the error from being added, but it wasn't the case. It seems that having errors on the model does not prevent the destroy from occurring.

So my question is, is there any way I can prevent the destroy from occurring using validations? I realize I could define a method that destroys only if the above condition is met, but it seems that a validation approach is a more elegant solution.


In case somebody stumbles here looking for Rails 5, returning false is not the way anymore. Use throw(:abort) instead, like in Martin Cabrera Diaubalick's answer.


Before Rails 5

If you return false from that before_destroy method, it will prevent the destruction.


This is a Rails 5 answer, if you return false it will give a deprecation warning: "Returning false in Active Record and Active Model callbacks will not implicitly halt a callback chain in Rails 5.1".

def confirm_presence_of_alternate_administratorship_in_school
  return if school.administrators.count(["administratorships.account_id != #{id}"]) > 0
  errors[:base] << 'The school must have at least one administrator'
  throw :abort
end


Returning false from your validation method will prevent the record from getting destroyed.

Example:

def confirm_presence_of_alternate_administratorship_in_school
  unless school.administrators.count(["administratorships.account_id != #{id}"]) > 0
    # errors.add_to_base() is deprecated in Rails 3. Instead do...
    errors.add(:base, "The school must have at least one administrator")

    # this will prevent the object from getting destroyed
    return false
  end
end

Side note: I was having trouble with this error message not being displayed. The validation would work and the object would not be deleted, but there would be no message letting me know what happened. The reason for this was that the controller was redirecting to the index view instead of rendering the delete view (if there is an error while creating a new user for example, it will render :action => 'new'. In this case there is no delete view). When this happened, the instance variable on which the error message was set (in errors.add(:base,"message")) is actually being reset, which destroys the error in the process.


For Rails 5, returningfalse won't halt the callback chain. You need to use throw(:abort)

belongs_to :account belongs_to :school

before_destroy :confirm_presence_of_alternate_administratorship_in_school

protected

def confirm_presence_of_alternate_administratorship_in_school
    unless school.administrators.count(["administratorships.account_id != #{id}"]) > 0
        errors.add_to_base "The school must have at least one administrator"
        throw(:abort)
    end
end


I ended up using code from here to create a can_destroy override on activerecord: https://gist.github.com/andhapp/1761098

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

This has the added benefit of making it trivial to hide/show a delete button on the ui

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜