简体   繁体   中英

undefined method `downcase' for nil:NilClass ruby on rails

class SessionsController < ApplicationController

    def new

    end

    def create
        user = User.find_by(email: params[:session][:email].downcase)
        if user && user.authenticate(params[:session][:password])
            session[:user_id] = user.id
            flash[:success] ="You have successfully logged in"
            redirect_to users_path(user)

        else
            flash.now[:danger] = "Invalid email or password"
            render 'new'

        end

    end

    def destroy
        session[:user_id] = nil
        flash[:success] = "Successfully logged out"
        redirect_to root_path   

    end
end

This is my error 这是我的错误

here is the routes.rb

get 'login', to: 'sessions#new'

post 'login', to: 'sessions#create'

delete 'logout', to: 'sessions#destroy'

There are two possibilities here.

One is that :session should be converted to :sessions .

If that doesn't solve it, try implementing strong parameters.

Basically, User.find_by(email: params[:session][:email] returns nil, because it can't find a user with these attributes.

The solution is to use strong parameters , so Active Record finds them

http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

Under your private section, you can define parameters

private

  def person_params
    params.require(:user).permit(:email, :password)
  end

The reason you need this is due to Rails Security

With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted. This means that you'll have to make a conscious decision about which attributes to allow for mass update. This is a better security practice to help prevent accidentally allowing users to update sensitive model attributes.

Add the strong params code above to your controller and it should fix your problem.

Look at your error message: params[:session][:email].downcase is nil. According to your params, it should be:

def create
  user = User.find_by(email: params[:session][:username].downcase)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM