我是rails的新手,我尝试使用匿名用户进行简单身份验证。我跟着this教程中,我有这样的错误:devise-rails的匿名用户
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用户从用户继承然后AnonymousUser有方法称为find_or_initialize_by_token
,但我不知道如何解决它。
您正在使用哪个rails版本? –
导轨3.2.1。这种方法是不是很好? –
是的,这是一个很好的。 –