我呼吁登录以下控制器:“缺少必需的钥匙” - Ruby on Rails的
class LoginController < ApplicationController
skip_before_action :verify_authenticity_token
protect_from_forgery
before_action :require_user
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
rescue ActiveRecord::RecordNotFound
end
def require_user
redirect_to login_path unless current_user
end
def show
end
def new
if session[:user]
@user = User.find(session[:user])
end
end
def destroy
reset_session
redirect_to "/login/acesso", notice: "Você foi deslogado"
end
def create
user = User.validate(login_params[:email], login_params[:senha])
if user
session[:user] = user.id
redirect_to "/home/inicio", notice: "login feito com sucesso"
else
redirect_to "/login/acesso", notice: "Dados incorretos"
end
end
private
def login_params
params.require(:login).permit(:email, :senha)
end
end
,这是我的路线:
Rails.application.routes.draw do
root 'login#new'
get '/home/inicio', to: 'home#index'
scope '/login' do
get '/acesso', to:'login#new'
post '/acessorecebendo', to:'login#create'
get '/sair', to:'login#destroy'
end
resources :login
resources :home
resources :produtos
resources :fornecedors
end
和错误:
No route matches {:action=>"show", :controller=>"login"}, missing required keys: [:id]
在线:
def require_user
redirect_to login_path unless current_user
end
的一点是:如果我删除行 “before_action:...” 在登录控制器中,我得到这个错误:
Couldn't find User with 'id'=2
的new.html.erb(登录的视图):
<% if flash[:notice] %>
<div class="notice"><%= flash[:notice] %></div>
<% end %>
<div class="login-page">
<div class="form">
<form class="register-form" action="/login/acessorecebendo" method="post">
<input type="text" name="login[email]" placeholder="Email"/>
<input type="password" name="login[senha]" placeholder="Senha"/>
<button>Cadastrar</button>
<p class="message">Já é registrado? <a href="#">Login</a></p>
</form>
<form class="login-form" action="/login/acessorecebendo" method="post">
<input type="text" name="login[email]" placeholder="email"/>
<input type="password" name="login[senha]" placeholder="password"/>
<button>login</button>
<p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
</form>
<% if session[:user] %>
<a href="/login/sair">Sair sessão <%= @user.nome %> </a>
<% end %>
</div>
</div>
因此,尝试解决这个问题,我需要做的方式来检查,如果有一个人登录与否并重定向到适当的视图。我试图做这样的事情之前,行动...
有人可以向我解释这一点,请? :\
我试图按照这种解决方案:Couldn't find User with id=1
但它没有工作..
莫非你添加了将你重定向到show方法的视图? –
什么看法?问题出在before_action方法:\ –
@SebastiánPalma我把登录控制器的视图 –