【发布时间】:2013-01-22 09:35:22
【问题描述】:
我是 Rails 新手,我尝试使用匿名用户进行简单的身份验证。我跟着this教程,我有这个错误:
undefined method `find_or_initialize_by_token'
这是我的 AnonymousUser 模型:
class AnonymousUser < User
ACCESSIBLE_ATTRS = [:name, :email]
attr_accessible *ACCESSIBLE_ATTRS, :type, :token, as: :registrant
def register(params)
params = params.merge(type: 'User', token: nil)
self.update_attributes(params, as: :registrant)
end
end
这是我的用户模型:
class User < ActiveRecord::Base
devise :database_authenticatable, :confirmable, :lockable, :recoverable,
:rememberable, :registerable, :trackable, :timeoutable, :validatable,
:token_authenticatable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
最后一个重要的是我的 ApplicationController 有这个错误:
class ApplicationController < ActionController::Base
protect_from_forgery
def authenticate_user!(*args)
current_user.present? || super(*args)
end
def current_user
super || AnonymousUser.find_or_initialize_by_token(anonymous_user_token).tap do |user|
user.save(validate: false) if user.new_record?
end
end
private
def anonymous_user_token
session[:user_token] ||= SecureRandom.hex(8)
end
end
有人告诉我,如果 AnonymousUser 用户从 User 继承,那么 AnonymousUser 有一个名为 find_or_initialize_by_token 的方法,但我不知道如何解决。
【问题讨论】:
-
你用的是哪个版本的rails?
-
导轨 3.2.1。这个方法的那个好版本吗?
标签: ruby-on-rails authentication registration lazy-evaluation