我是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。這種方法是不是很好? –
是的,這是一個很好的。 –