【问题标题】:Devise authentication - devise_error_messages! in a view causes "undefined method `errors' for nil:NilClass设计身份验证 - devise_error_messages!在视图中导致“nil:NilClass 的未定义方法‘错误’
【发布时间】:2012-09-30 22:04:00
【问题描述】:

设计错误消息!看原因

undefined method 'errors' for nil:NilClass

create 方法中的render :new 之后。这开始发生在我从“Devise::RegistrationsController”而不是“ApplicationController”继承 RegistrationsController 之后。 “新”方法的初始渲染不会导致任何异常。

重写的注册控制器:

class RegistrationsController < Devise::RegistrationsController
  def create
    begin
      raise I18n.t("registration_disabled") unless registration_enabled?
      ....................
    rescue => ex
      flash[:alert] = ex.message
      render :new
    end
  end
end

视图registrations/new.html.erb:

<h2><%= I18n.t("sign_up_title") %></h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

    <div><%= f.label :login, I18n.t("the_login") %> <span class="mandatory">*</span><br />
      <%= f.text_field :login %></div>

    <div><%= f.label :password, I18n.t("password") %> <span class="mandatory">*</span><br />
      <%= f.password_field :password %></div>

    <div><%= f.label :password_confirmation, I18n.t("password_confirmation") %> <span class="mandatory">*</span><br />
      <%= f.password_field :password_confirmation %></div>

    <div><%= f.submit from_admin? ? I18n.t("sign_up_other") : I18n.t("sign_up") %></div>
    <p class="mandatory">* - <%= I18n.t("mandatory_fields") %></p>
<% end %>

<%= render "devise/links" %>

【问题讨论】:

    标签: ruby-on-rails exception devise registration


    【解决方案1】:

    我相信这是因为您在创建对象(设计称之为资源)之前引发了异常。 devise_error_messages 助手需要它。

    如果你想阻止访问注册,还有其他方法可以实现:

    一种方法可能是:

    class RegistrationsController < Devise::RegistrationsController
      def create
        if registration_enabled?
          super
        else
          flash[:alert] = I18n.t("registration_disabled")
          redirect_to action: :new
        end
      end
    end
    

    我不能 100% 确定这是否可行,但这个想法是在用户无法注册时使用 flash 渲染视图,因此这将表现为“初始渲染”

    编辑:其实我相信改变你的

    render action: :new
    

    redirect_to action: :new
    

    足以防止错误,因为 redirect_to 将执行方法,而渲染器只渲染关联视图。

    【讨论】:

    • 这个想法是registration_enabled?不是可能导致异常的唯一原因。它可能是由于一些“自然”原因引起的,例如,在执行 user.save 时出错!或其他东西,所有这些情况都应该以正确的方式处理,即 - 通过在活动页面上显示错误消息而不是崩溃。
    • 顺便说一句,插入“软”条件退出而不是引发异常并没有改变任何东西。它一执行“render :new”就会崩溃。 "redirect_to :action => :new" 完成这项工作。
    • 是的,后来我意识到“软”条件实际上是没有用的。
    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    相关资源
    最近更新 更多