如果Session不是Active Record模型,如何处理错误:session?

时间:2016-09-06 21:11:54

标签: ruby-on-rails

没有会话模型。除了刷新一般故障通知之外,我怎样才能创建有关表单提交为何不成功的特定错误?

  

回想一下第7.3.3节,我们使用用户模型错误消息显示了注册错误。这些错误与特定的Active Record对象相关联,但此策略在此处不起作用,因为会话不是Active Record模型。相反,我们将在闪存中放入一条消息,以便在登录失败时显示。   Rails Tutorial

控制器

class SessionsController < ApplicationController

  def new
  end

   def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      if user.activated?
        log_in user
        params[:session][:remember_me] == '1' ? remember(user) : forget(user)
        redirect_back_or user
      else
        message  = "Account not activated. "
        message += "Check your email for the activation link."
        flash[:warning] = message
        redirect_to root_url
      end
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

表格

<%= form_for(:session, url: login_path) do |f| %>
  <%= f.label :email %>
  <%= f.email_field :email, class: 'form-control' %>
  <%= f.label :password %>
  <%= f.password_field :password, class: 'form-control' %>
  <%= f.submit "Sign in", class: "btn btn-primary sessions" %>
<% end %>

参数传递为:

  

开始POST&#34; / login&#34;在2016-09-06 17:33:59 +0000发表于68.204.49.62   2016-09-06T17:33:59.165393 + 00:00 app [web.1]:参数:{&#34; utf8&#34; =&gt;&#34;✓&#34;,&#34; authenticity_token&# 34; =&gt;&#34; DhKuJCjbeVgBOsQiujgd34540Vk3i5ouRFpAm8JnU9ZKWlMZhxN7VPnWJrfuuKmgFNTvsDfJNTXNLRpI1pHNebA ==&#34;,&#34; session&#34; =&gt; {&#34; email&#34; =&gt;&#34; simondang@gmail.com&# 34;,&#34;密码&#34; =&gt;&#34; [过滤]&#34;,&#34; remember_me&#34; =&gt;&#34; 0&#34;},&#34 ; commit&#34; =&gt;&#34;登录&#34;}

编辑:所以我想过这样做?

def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user 
      if user.authenticate(params[:session][:password])
        if user.activated?
          log_in user
          params[:session][:remember_me] == '1' ? remember(user) : forget(user)
          flash.now[:success] = "Great job dude!"
          redirect_back_or user
        elsif !user.activated?
          message  = "Account not activated. "
          message += "Check your email for the activation link."
          flash[:warning] = message
          redirect_to root_url
        else
         flash.now[:danger] = "Something went wrong, please try again."
         render 'new'  
        end
      elsif !user.authenticate(params[:session][:password])
        flash.now[:danger] = "Incorrect password."
        render 'new'  
      else 
        flash.now[:danger] = "Something went wrong. Please try again."
        render 'new'
      end
    elsif !user 
      flash.now[:danger] = 'Incorrect email'
      render 'new'
    else  
      flash.now[:danger] = "Something went wrong, please try again or contact support."
      render 'new'
    end
  end

这可以通过试用/错误测试,但看起来不太理想/干。

0 个答案:

没有答案