花了一些时间来解决这个问题,我已经没有选择来修复这个错误了。我已经从M Hartl的RoR教程中获得了第8章(登录/退出)。有类似的问题(Undefined method `remember_token=' 'find_by_remember_token' - Chapter 8 Ruby on Rails Tutorial),我已经尝试了那里给出的所有答案,但没有用。
方法remember_token在我的user.rb文件中定义:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
has_secure_password
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 4 }
validates :password_confirmation, presence: true
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt (User.new_remember_token)
end
end
我的用户控制器:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params) # not the final implementation
if @user.save
# Handle a successful save.
sign_in @user
flash[:success] = "Welcome to Story Escape!"
redirect_to @user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
我的会话控制器:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to user
else
flash.now[:error] = "Invalid email/password combination"
render 'new'
end
def destroy
end
end
end
我的sessions_helper.rb:
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find_by(remember_token: remember_token)
end
end
我是Ruby和Rails的新手(以及一般的编码),所以任何线索都会有很大的帮助。
答案 0 :(得分:3)
就我而言,这个错误是一个愚蠢的错误:不添加:
remember_token = User.encrypt(cookies[:remember_token])
我在sessions_helper.rb文件中定义了current_user。
答案 1 :(得分:1)
听起来您忘记生成(或应用)将remember_token
属性添加到User
模型的迁移。
rails generate migration add_remember_token_to_users remember_token:string
rake db:migrate
rake db:test:prepare