简体   繁体   中英

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

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM