In rails, how can I find out what caused a .save() to fail, other than validation errors?

Ruby on-RailsActiverecord

Ruby on-Rails Problem Overview


I have an ActiveRecord model which is returning true from valid? (and .errors is empty), but is returning false from save(). If the model instance is valid, how can I find out what's causing the save to fail?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

If @user.save (for example) returns false, then just run this to get all the errors:

@user.errors.full_messages

Solution 2 - Ruby on-Rails

Try using the bang version save! (with an exclamation mark at the end) and inspecting the resulting error.

Solution 3 - Ruby on-Rails

Check all your callbacks.

I had a problem like this where I had and "after_validate" method that was failing after I had made a bunch of changes to the model. The model was valid but the "after_validate" was returning false, so if I used model.valid it said true, but then if I saved it gave me validation errors (passed through from the after_validate callback). It was weird.

Look at the application trace and you should be able to see what line of code is raising the exception.

Solution 4 - Ruby on-Rails

Yea, I fixed this issue by making sure I return true in all my before_* callbacks then it starts working :)

Solution 5 - Ruby on-Rails

Make sure you aren't trying to save a deleted record.

I had the same issue. But unlike the selected answer - my issue wasn't callbacks related.

In my case I had tried to save to a deleted record (deleted from DB).

@user = User.new
@user.save! # user saved to DB
@user.persisted? # true

@user.destroy # user deleted from DB
@user.persisted? # false, user still has its id

@user.valid? # return true
@user.errors # empty
@user.save # return false
@user.save! # raise ActiveRecord::RecordNotSaved

Solution 6 - Ruby on-Rails

The problem I had was that I had forgotten to add the validation to the model.

class ContactGroup < ActiveRecord::Base
  validates_presence_of :name
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkdtView Question on Stackoverflow
Solution 1 - Ruby on-RailsSam AlexView Answer on Stackoverflow
Solution 2 - Ruby on-RailsAndy LindemanView Answer on Stackoverflow
Solution 3 - Ruby on-RailsAndrewView Answer on Stackoverflow
Solution 4 - Ruby on-RailsPencilcheckView Answer on Stackoverflow
Solution 5 - Ruby on-RailsRokoView Answer on Stackoverflow
Solution 6 - Ruby on-RailsIan VaughanView Answer on Stackoverflow