Ruby on Rails ActionView :: Template :: Error

时间:2017-11-11 15:32:15

标签: ruby-on-rails ruby-on-rails-5 railstutorial.org

我正在关注Ruby on Rails教程并遇到一个错误,该错误完整地说:ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"password_resets", :email=>"steve@example.com", :id=>nil}, possible unmatched constraints: [:id]

这涉及允许用户从表单重置其密码的代码。错误是指路线,因此我将从routes.rb开始:

get 'sessions/new'

root    'static_pages#home'
get     '/about',     to: 'static_pages#about'
get     '/contact',   to: 'static_pages#contact'
get     '/help',      to: 'static_pages#help'

get     '/signup',    to: 'users#new'
post    '/signup',    to: 'users#create'
get     '/login',     to: 'sessions#new'
post    '/login',     to: 'sessions#create'
delete  '/logout',    to: 'sessions#destroy'

resources :users
resources :account_activations, only: [:edit]
resources :password_resets,     only: [:new, :create, :edit, :update]

错误提到控制器中空白的edit操作。重置功能来自create中的password_resets_controller操作,如:

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] = "Email sent with reset instructions"
    redirect_to root_url
  else
    flash[:danger] = "Email address not found"
    render 'new'
  end
end

def edit
end

这会使用表单上提交的电子邮件将用户从数据库中拉出来。然后从模型中调用两个方法来完成重置过程。首先,create_reset_digest方法创建一个令牌并更新该用户的属性:

def create_reset_digest
  self.activation_token = User.new_token # <- error here; wrong attribute
  update_attributes(reset_digest: User.digest(reset_token), 
                    reset_sent_at: Time.zone.now)
end

然后,它发送密码重置电子邮件:

def send_password_reset_email
  UserMailer.password_reset(self).deliver_now
end

在电子邮件中,提到edit_password_reset_url我认为是导致此错误的原因。该电子邮件的视图是:

<%= link_to "Password reset", edit_password_reset_url(@user.reset_token, 
                                                      email: @user.email) %>

此方法获取用户的重置令牌和电子邮件,并将其显示在用户可以访问的URL中以重置其密码。该网址采用http://example.com/password_resets/reset_token/edit?email="steve%40example.com"

形式

错误意味着存在一个无法匹配的约束; [:id]不匹配 - 实际上,它显示为nil:id=>nil来自哪里?如何才能将其与用户ID相匹配?我可以在错误消息中暗示其他任何内容吗?

当我进行初步测试时,我收到了这个错误:

test "password_reset" do
  @user.activation_token = User.new_token
  mail = UserMailer.password_reset(@user)
  assert_equal "Password reset",        mail.subject
  assert_equal ["to@example.org"],      mail.to
  assert_equal ["noreply@example.com"], mail.from
  assert_match "Hi",                    mail.body.encoded
end

当我使用网络应用程序启动密码重置时,我得到一个稍微不同的错误,因为它是ActionController::UrlGenerationError in PasswordResets#create。这突出显示了edit_password_reset_url((@user.reset_token, email: @user.email)方法。我已经检查了这本书,看不出这行是不正确的。

欢迎您的建议。

1 个答案:

答案 0 :(得分:1)

您似乎未设置@user.reset_token(在link_to中使用)?我看到像self.activation_token = User.new_token这样的东西。但不像self.reset_token = ....那样。