我有两个控制器:管理员和客户,还有一个用于处理登录和身份验证的调用会话。我正在尝试使用一种登录表单,以便当管理员登录时,他们会被重定向到他们所在的网站部分,如果客户登录,他们会被带到他们的部分。
编辑:将参数更改为通过电子邮件登录,但现在当我尝试以客户身份登录时出现错误 No route matches {:action=>"show", :controller=>"customers"} :S!!
代码:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
customer = Customer.find_by_email(params[:email])
if user and user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to admin_url
elsif customer and customer.authenticate(params[:password])
session[:customer_id] = customer.id
redirect to customer_url
else
redirect_to login_url, alert: "Invalid user/password combination"
end
end
def destroy
session[:user_id] = nil
session[:customer_id] = nil
redirect_to store_url, notice: "Logged out"
end
end
登录页面的代码(存储在 app/sessions/new.html.erb 中):
<div class="depot_form">
<% if flash[:alert] %>
<p id="notice"><%= flash[:alert] %></p>
<% end %>
<%= form_tag do %>
<fieldset>
<legend>Please Log In</legend>
<div>
<%= label_tag :email, 'Email:' %>
<%= text_field_tag :email, params[:email] %>
</div>
<div>
<%= label_tag :password, 'Password:' %>
<%= password_field_tag :password, params[:password] %>
</div>
<div>
<%= submit_tag "Login" %>
</div>
</fieldset>
<% end %>
</div>
另外,如果相关,我在 config/routes 文件中有这个:
controller :sessions do
get 'login' => :new
post 'login' => :create
delete 'logout' => :destroy
end
编辑:将参数更改为通过电子邮件登录,但现在当我尝试以客户身份登录时出现错误 No route matches {:action=>"show", :controller=>"customers"} :S!!