Search code examples
rubyactiverecordsinatrasinatra-activerecord

Why won't my Ruby app save instances to the database?


I have a Sinatra application using ActiveRecord in progress. Whenever I run User.create an instance is created but no id is saved. I've tried rake db:reset but nothing changes. Please help me solve this!

An example in Pry:

 pry(#<AlbumController>)> User.create
=> #<User:0x00007fffea2bed18 id: nil, name: nil, username: nil, email: nil, password_digest: nil>

To clarify, this along with numerous other tables are migrated and still have problems, but if I can fix User#create then I'll probably be able to fix all of the others. Also, everything worked out smoothly until I checked this morning. I don't know if some Ruby or Visual Studio update messed it up or not so if anyone knows something about that please let me know.

Also, for further details you can check out the code directly through my Github Repository


Solution

  • The only reason create fails is because of a validation failure, or something that interrupted the save such as a before_save popped and exception.

    To find out what the issue is the easiest way is:

    User.create!
    

    That will either succeed and create a user, or raise an exception.

    If you've attempted a save and now want to know more about why it failed:

    user = User.create
    user.persisted? # Returns true if created, false otherwise
    user.errors.full_messages
    

    Where that's a lot easier to read.

    The most common cause of failure is a validation failure, as in you skipped a required field.