devise_error_messages!在视图中导致
undefined method 'errors' for nil:NilClass
在render :new
方法中create
之后。这是在我从“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" %>
答案 0 :(得分:2)
我相信这是因为你在创建对象(设计称为资源)之前引发了异常。 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
我不是百分之百确定这是否可行但是如果用户无法注册,这个想法是用flash渲染视图,所以这将表现为“初始渲染”
编辑:其实我相信改变你的render action: :new
到
redirect_to action: :new
足以防止错误,因为redirect_to将执行方法,而渲染只是渲染关联视图。