Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails : model.save returns false but models.errors is an empty hash

I have a model object on which .save is returning false. It subsequently has a .errors property which is an empty hash. Shouldn't the hash contain a list of what went wrong? How else can I determine why the save is not working?

TY, Fred

like image 790
fred basset Avatar asked Dec 17 '25 03:12

fred basset


2 Answers

This means that one of your callbacks is probably stopping the save, but isn't listing a validation error.

Check the return values, especially of any before_ callbacks and make sure that they are not returning false

If they return false, then active record will stop future callbacks and return false from the save.

You can read a little bit about it here under "canceling callbacks"

like image 59
Daniel Evans Avatar answered Dec 19 '25 16:12

Daniel Evans


1) Disable before_create, before_save, before_update and check where it saves the day

2) If rollback was caused by one of those methods, check that those methods return true when you don't plan to rollback.

For example if you set default value for boolean field to avoid nil, you would probably do it this way

def set_defaults_before_create
  self.my_boolean_field ||= false
end

In this example method set_defaults_before_create always returns false and thus rollbacks your transaction. So refactor it to return true

def set_defaults_before_create
  self.my_boolean_field ||= false
  true
end
like image 21
Sergiy Seletskyy Avatar answered Dec 19 '25 18:12

Sergiy Seletskyy