未定义的方法`[]' for nil:NilClass用于登录用户名

时间:2015-11-22 01:13:53

标签: ruby-on-rails authentication login username

目标是使用用户名而不是电子邮件登录...目前正在关注Micheal Hartl教程。下面是我的会话控制器和用户模型,请问我哪里出错?

SessionController:

    def create
      user = User.find_by_username(username: params[:session][:username])
      if user && user.authenticate(params[:session][:password])
        log_in user
        redirect_to user
      else
        flash.now[:danger] = 'Invalid username/password combination' 
        render 'new'
      end
    end

用户模型:

class User < ActiveRecord::Base
    before_save { email.downcase! }
    before_save { username.downcase! }

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    validates :name, presence: true, length: { maximum: 40 }
    validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
    validates :location, presence: true, length: { maximum: 40 }
    validates :username, presence: true, length: { maximum: 15 }, uniqueness: true

    has_secure_password
    validates :password, presence: true, length: { minimum: 6 }
end

0 个答案:

没有答案