Tim
Tim

Reputation: 2285

rails 3 - accepts nested attributes for before destroy validation

I have a teachers model that accepts_nested_attributes_for klasses. I don't want to be able to delete the klass if there are users in the klass and I want to print a validation message.

This is what I have...

class Teacher < ActiveRecord::Base
    accepts_nested_attributes_for :klasses, :reject_if => proc { |a| a['name'].blank? }, :allow_destroy => true
end

class Klass < ActiveRecord::Base

    belongs_to :teacher
    has_many :users
    before_destroy :reject_if_has_users

    private 

    def reject_if_has_users
      if users.length > 0
        errors.add_to_base "You cannot delete this class as it contains users."
        false
      else
        true
      end
    end

end

I want the validation to fail when I try removing a klass from a teacher that contains users when I am using accepts_nested_attributes_for and passing in a "klasses_attributes"=>{"0"=>{"name"=>"test", "_destroy"=>"1", "id"=>"17183"} hash.

The above method will prevent the klass from being removed if I don't have the error.add_to_base line. It won't however cause a validation message to be shown. When I have that line, it doesn't prevent the deletion.

Thanks,

Tim

Upvotes: 2

Views: 2641

Answers (1)

Mischa
Mischa

Reputation: 43298

Validation doesn't take place when deleting a record, only when saving a record. The way I handled this in one of my projects is raising an exception in the model and then rescueing from that exception in my controller and showing a flash alert. Like this:

Model:

class Klass < ActiveRecord::Base
  before_destroy :reject_if_has_users

  private 

  def reject_if_has_users
    raise "You cannot delete this class as it contains users." if users.length > 0
  end
end

Teachers controller:

def update
  # Code for updating the teacher
rescue RuntimeError => e
  redirect_to teacher_url(@teacher, :alert => e.message) and return false
end

Upvotes: 1

Related Questions