2016-10-21 3 views
0

저는 Michael Hartl의 Learn Rails 튜토리얼을 수정했습니다. 저는 6 장의 모델링 사용자입니다. 어떤 이유로 ActiveRecord에서 사용자가 올바르게 작성되지 않아 저장하지 않습니다. 레일 5 : ActiveRecord가 레코드를 생성하지 않습니다.

나는

user_1 = User.create(id: 1, name: 'Han Solo', email: '[email protected]') 
user_2 = User.create(id: 2, name: 'Luke Skywalker', email: '[email protected]') 

가 그럼 난 rails db:seed를 실행 내 seeds.rb 파일에서 이러한 사용자를 배치,하지만 난 내 rails console에 가면, 어떤 사용자가 생성되지 않았습니다처럼 나타납니다

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 사용자를 모델

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+\-.][email protected][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 

아무도 무슨 일이 벌어지고 있는지 알 수 없습니까?

+0

데이터베이스에 이미 해당 사용자가 있습니까? 'valid? '를 체크했을 때 나타납니다. 전자 메일 주소가 이미 사용 되었기 때문에 false를 반환합니다. – rdubya

+1

예를 들어 실제 Gmail 주소 대신 IANA 샌드 박스 도메인'@ example.com'을 사용하십시오. 주소를 소유 한 사람이 스팸봇에 의해 수확되는 것을 막아줍니다. – max

+0

을 호출 한 후'user.valid?'를 호출하면'user.errors.full_messages'를 호출하여 같은 것을 방지 할 수 있습니다. –

답변

1

좋아, 알아 냈어.

  1. 나는 시드 .rb에서 이드를 꺼냈다. id 속성을 가져 왔을 때 유효한 비밀번호가없는 사용자의 오류가 발생하기 시작했습니다. 그런 다음 암호와 암호 확인을 추가하여 내 사용자 모델에 설정된 암호 표준을 준수했습니다.
  2. 내 모델을 업데이트하고 비밀번호 확인을 추가했습니다.

은 여기 내 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+\-.][email protected][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 

그리고 seeds.rb

user_1 = User.create!(name: 'Han Solo', email: '[email protected]', password: 'Password123!', password_confirmation: 'Password123!') 
user_2 = User.create!(name: 'Luke Skywalker', email: '[email protected]', password: 'Password123!', password_confirmation: 'Password123!') 

나는 사용자가, 레일 콘솔을 열고 User.delete_all를 실행하고, 그들이 닦아보고가 제대로 생성되는 것을 테스트 업데이트 SQL 레코드

+0

레코드에 ID를 할당하지 마십시오. 데이터베이스는 id 열을 자동으로 증가시키고 ID를 INSERT SQL 쿼리의 일부로 반환합니다. – max

+0

다시 확인해 주셔서 감사합니다. 나는 그것을 염두에 두겠다. –

관련 문제