我希望在用户注册时发送电子邮件。此电子邮件应包含链接,可将帐户更改为完整用户。我希望此电子邮件链接是安全性的标记。
目前:我收到要发送的电子邮件,但是当我点击该链接时出现此错误。
在UsersController#accept_invitation 中的Couldn't find User without an ID
已发送链接 http://localhost:3000/users/accept_invitation.P3Iu5-21nlISmdu2TlQ08w
user_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
UserMailer.registration_confirmation(@user).deliver
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
def accept_invitation
@user = User.find(params[:email_token])
@user.email_activation_token = true
redirect_to root_url, :notice => "Email has been verified."
end
end
end
registration_confirmation.html.haml
Confirm your email address please!
= accept_invitation_users_url(@user.email_token)
user.rb模型
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
before_save { |user| user.email = email.downcase }
before_create { generate_token(:auth_token) }
before_create { generate_token(:email_token) }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
VALID_PASSWORD_REGEX = /^(?=.*[a-zA-Z])(?=.*[0-9]).{6,}$/
validates_confirmation_of :password
validates :password, :on => :create, presence: true, format: { with: VALID_PASSWORD_REGEX }
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
end
答案 0 :(得分:2)
你得到了这个错误,因为在你的accept_invitation方法中,调用期望id的用户模型上的find,并且你传递了email_token参数。
试试这个..
def accept_invitation
@user = User.find_by_email_token(params[:email_token])
@user.email_activation_token = true
@user.save
redirect_to root_url, :notice => "Email has been verified."
end
答案 1 :(得分:2)
在你的控制器中你正在做:
User.find(params[:email_token])
这将尝试查找id等于params传入的电子邮件令牌的用户。我认为你真的想做更多的事情:
User.find_by_email_token(params[:email_token])
如果找不到具有给定id的记录,则find方法将引发异常。您需要能够通过令牌查找或从令牌获取记录的ID。