我有我的rails应用程序,当我尝试登录时(我创建了名为“test”的用户)我在控制台中看到了这个:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"tlKwtMBNJ4LzJuJq13bUscAGpumdr+HVmUlGlfIudT9032DMXNxqa0d2VCxCvDZRDe1D6pFfaTafSRiL6tUvhw==", "session"=>{"login"=>"", "password"=>"[FILTERED]"}, "commit"=>"Log in"}
User Load (1.7ms) SELECT `users`.* FROM `users` WHERE `users`.`login` IS NULL LIMIT 1
我看到在会话参数应用程序无法获取用户登录(也可能是密码)。以下是我的用户和会话控制器:
class UsersController < ApplicationController
before_action :require_admin
def new
@users = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
current_user = @user.id
redirect_to @user
else
redirect_to '/login'
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :login)
end
end
会话控制器:
class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by_login(params[:login])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect_to '/'
else
flash[:error] = 'err'
redirect_to '/login'
end
end
def destroy
session[:user_id] = nil
redirect_to root_url
end
end
我还测试了用户创建,并且记录在数据库中。 @update这是我对登录表单的看法
<%= form_for(:session, url: login_path) do |f| %>
<div class="hidden-sm hidden-xs col-md-12 col-lg-12 ">
<%= f.text_field :login, :placeholder => "login" %>
<%= f.password_field :password, :placeholder => "password" %>
<%= f.submit "Log in", class: "btn-submit"%>
</div>
答案 0 :(得分:1)
您的params中嵌套了哈希值(login
param位于session
键下)。
试试
def create
@user = User.find_by_login(params[:session][:login])
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
redirect_to '/'
else
flash[:error] = 'err'
redirect_to '/login'
end
end
此外,在您的示例login
param为空 - 我猜它不是从表单提供的。
@update:使用表单标签
<%= form_tag login_path, method: :post do %>
<div class="hidden-sm hidden-xs col-md-12 col-lg-12 ">
<%= text_field_tag :login, :placeholder => "login" %>
<%= password_field_tag :password, :placeholder => "password" %>
<%= submit_tag "Log in", class: "btn-submit"%>
</div>
<% end %>
和create方法(因为params不再嵌套):
def create
@user = User.find_by_login(params[:login])
if @user && @user.authenticate(params[:password])
session[:user_id] = @user.id
redirect_to '/'
else
flash[:error] = 'err'
redirect_to '/login'
end
end