我不确定此错误消息的来源。我正在关注Hartl的铁路教程,但要将其改编为我自己的应用程序。我正在编写第10章,并且正在添加密码重置。
当我收到错误时:在服务器上发送带有重置密码链接的电子邮件。然后我在浏览器中输入链接并收到以下错误消息:
undefined local variable or method `object'
Extracted source (around line #2):
<% if object.errors.any? %>
这是指共享错误消息文件,该文件未经过更改而且之前没有出现问题。 我不知道该送你去看看可能是什么原因。
\视图\ shared_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
views \ passwords_resets \ edit.html.erb(跟踪链接时调用的页面):
<% provide(:title, 'Reset password') %>
<h1 class="center">Reset password</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@user, url: password_reset_path(params[:id])) do |f| %>
<%= render 'shared/error_messages' %>
<%= hidden_field_tag :email, @user.email %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.submit "Update password", class: "btn btn-primary" %>
<% end %>
</div>
</div>
应用\控制器\ password_resets_controller.rb:
class PasswordResetsController < ApplicationController
before_action :get_user, only: [:edit, :update]
before_action :valid_user, only: [:edit, :update]
def new
end
def create
@user = User.find_by(email: params[:password_reset][:email].downcase)
if @user
@user.create_reset_digest
@user.send_password_reset_email
flash[:info] = "An email is sent to you with password reset instructions"
redirect_to root_url
else
flash.now[:danger] = "Email address not found"
render 'new'
end
end
def edit
end
def update
if password_blank?
flash.now[:danger] = "Password can't be blank"
render 'edit'
elsif @user.update_attributes(user_params)
log_in @user
flash[:success] = "Password has been reset."
redirect_to @user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:password, :password_confirmation)
end
# Returns true if password is blank.
def password_blank?
params[:user][:password].blank?
end
# Before filters
def get_user
@user = User.find_by(email: params[:email])
end
# Confirms a valid user.
def valid_user
unless (@user && @user.activated? && @user.authenticated?(:reset, params[:id]))
redirect_to root_url
end
# Checks expiration of reset token.
def check_expiration
if @user.password_reset_expired?
flash[:danger] = "Password reset has expired."
redirect_to new_password_reset_url
end
end
end
更新:在撰写此问题时,我发现当我从\ views \ shared_error_messages.html.erb中删除行<%= render 'shared/error_messages' %>
时,我不再遇到问题,新视图显示正确。它然后正常工作,我可以更改密码。但是,错误消息不再显示(例如,当密码和密码确认不匹配时)。怎么办?
答案 0 :(得分:0)
渲染时,必须将对象传递给错误消息模板。您对呈现错误消息模板的调用现在应包括object: f.object
,如下所示:
<%= render "shared/error_messages", object: f.object %>
答案 1 :(得分:0)
你的部分对&#34;对象&#34;一无所知。您必须将@user对象传递给partial:
<%= render 'shared/error_messages', locals: {object: @user %>