1

before_* callbacks can halt execution by returning false.

I have 3 before_destroy callbacks on a model to halt destruction for several possible reasons. I'd like to tell the user which reason it is, but I'll I get back from the model.destroy is false. How can I send a message out of the model, or determine from the controller which before_destroy callback halted execution?

pixelearth
  • 13,674
  • 10
  • 62
  • 110

3 Answers3

1

This is a nice question. I don't know if there is a good way to do it. The only thing that comes to my mind is using errors[:base] but it sounds a bit of a hack.

lucapette
  • 20,564
  • 6
  • 65
  • 59
1

There are few good answers here - How do I 'validate' on destroy in rails.

Basicly the solutions will be

errors.add_to_base "Name of the error"

OR

You can define attr_accessor in the model and set them appropriately , even thought I think that this is not the most DRY way , because the object already has the errors attribute hash which should hold the errors.

EX is:

attr_accessor :before_save_error1
attr_accessor :before_save_error2
attr_accessor :before_save_error3

before_destroy :check_for_errors

def check_for_errors 
  error = false
  if error1 # some condition here 
    self.before_save_error1 = true
    error = true 
  elsif error2 # some condition here 
    self.before_save_error2 = true
    error = true
  elseif error3 # some condition here 
    self.before_save_error3 = true
    error = true   
  end 

  error
end 
Community
  • 1
  • 1
VelLes
  • 1,032
  • 1
  • 10
  • 19
0

Found the answer. Use:

errors.add :my_key, 'my msg'

Errors is just a hash and can handle any key. Just make sure you don't have name collisions with your attributes.

pixelearth
  • 13,674
  • 10
  • 62
  • 110