0

I'm working on a modified version of Michael Hartl's Learn Rails Tutorial. I'm on chapter 6, modeling users. For some reason, my users aren't creating correctly on ActiveRecord and aren't saving at all.

I placed these users in my seeds.rb file

user_1 = User.create(id: 1, name: 'Han Solo', email: 'han@example.com')
user_2 = User.create(id: 2, name: 'Luke Skywalker', email: 'luke@example.com')

Then I run rails db:seed, but if I go to my rails console, it appears like no users have been created:

Running via Spring preloader in process 24358
Loading development environment (Rails 5.0.0.1)
2.2.2 :001 > User.delete_all
  SQL (1.1ms)  DELETE FROM "users"
 => 0 
2.2.2 :002 > 

user.rb User Model

class User < ApplicationRecord
    #Ensure Email Uniqueness by Downcasing the Email Attribute
    before_save {self.email = email.downcase }
    #validates name, presence, and length
    validates :name, presence: true, length: { maximum: 100 }
    #Validate presence, length, format, and uniqueness (ignoring case)
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: {maximum: 250}, format: {with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false}
    #Adds ability to save securely hashed password_digest attribute to database
    #Adds a pair of virtual attributes (password and password_confirmation)
    #including presence validations upon object creation and a validation
    #requiring that they match
    #adds authenticate method that returns the user when the password is correct (and false otherwise)
    has_secure_password
    PASSWORD_FORMAT = /\A
        (?=.{8,})          # Must contain 8 or more characters
        (?=.*\d)           # Must contain a digit
        (?=.*[a-z])        # Must contain a lower case character
        (?=.*[A-Z])        # Must contain an upper case character
        (?=.*[[:^alnum:]]) # Must contain a symbol
    /x
    validates :password, presence: true, length: {minimum: 8}, format: {with: PASSWORD_FORMAT}

end

schema.rb

ActiveRecord::Schema.define(version: 20161020211218) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "password_digest"
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
  end

end

Anyone have any idea what might be going on?

zasman
  • 446
  • 1
  • 8
  • 28
  • Do you already have that user in your database? It appears when you check `valid?` it is returning false because the email address is already used. – rdubya Oct 21 '16 at 01:46
  • 1
    Please the IANA sandbox domain `@example.com` instead of real gmail addresses for examples. It saves whoever owns the address from getting harvested by spambots. – max Oct 21 '16 at 01:48
  • after calling `user.valid?` call `user.errors.full_messages` to see what's preventing the same. – max pleaner Oct 21 '16 at 01:50
  • I think you may be confused by the `user.valid?` line. `=> false ` is the return value of the `.valid?` method call - not the database query. – max Oct 21 '16 at 01:54
  • Hey check out my code I just updated it showing when I run rails db:seed and then rails console and User.delete_all to delete the users I just created, it seems like they're not there. – zasman Oct 21 '16 at 01:55
  • `User.create!( id: 1, name: 'Han Solo', email: 'han@example.com' )` You don't want to wrap the attributes in a array. The `{}` is optional since ruby treats the arguments as a hash anyways. Use `create!` in your seeds file as it will raise an exception and tell you if something is wrong. – max Oct 21 '16 at 02:03
  • @max that didnt' fix it – zasman Oct 21 '16 at 02:06
  • Did you try changing it to `create!`? Also don't pass the id. The database assigns it automatically. – max Oct 21 '16 at 02:07
  • hey @max I figured it out and posted my answer thanks! – zasman Oct 21 '16 at 02:20

1 Answers1

2

Ok, I figured it out.

  1. I took out id from the seeds.rb. When I took out the id attribute, it started throwing me the error of the user not having a valid password. I then added a password and password confirmation to conform to password standards set in my user model.
  2. Updated my model and added a password confirmation.

Here's my updated user.rb

class User < ApplicationRecord
    #Ensure Email Uniqueness by Downcasing the Email Attribute
    before_save {self.email = email.downcase }
    #validates name, presence, and length
    validates :name, presence: true, length: { maximum: 100 }
    #Validate presence, length, format, and uniqueness (ignoring case)
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: {maximum: 250}, format: {with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false}
    #Adds ability to save securely hashed password_digest attribute to database
    #Adds a pair of virtual attributes (password and password_confirmation)
    #including presence validations upon object creation and a validation
    #requiring that they match
    #adds authenticate method that returns the user when the password is correct (and false otherwise)
    has_secure_password
    PASSWORD_FORMAT = /\A
        (?=.{8,})          # Must contain 8 or more characters
        (?=.*\d)           # Must contain a digit
        (?=.*[a-z])        # Must contain a lower case character
        (?=.*[A-Z])        # Must contain an upper case character
        (?=.*[[:^alnum:]]) # Must contain a symbol
    /x
    validates :password, presence: true, length: {minimum: 8}, format: {with: PASSWORD_FORMAT}
    validates :password_confirmation, presence: true
end

And seeds.rb

user_1 = User.create!(name: 'Han Solo', email: 'han@example.com', password: 'Password123!', password_confirmation: 'Password123!')
user_2 = User.create!(name: 'Luke Skywalker', email: 'luke@example.com', password: 'Password123!', password_confirmation: 'Password123!')

I tested that the user is being created properly by opening up the rails console, running User.delete_all , and seeing them wiped off the SQL record.

zasman
  • 446
  • 1
  • 8
  • 28
  • You never assign IDs to records - the database auto-increments the id column and it returns the id as part of the INSERT sql query. – max Oct 21 '16 at 02:30
  • Thanks again for reaffirming that! I'll keep that in mind. – zasman Oct 21 '16 at 02:35