【问题标题】:Devise ensure_authentication_token reports undefined method设计 ensure_authentication_token 报告未定义的方法
【发布时间】:2012-01-03 18:15:48
【问题描述】:

用户模型看起来像这样:

before_save :ensure_authentication_token

devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, :validatable
  :token_authenticatable

attr_accessible :email, :password, :password_confirmation, 
                :remember_me, :first_name, :last_name, 
                :cell_phone, :city, :state, :country, :user_type

在 devise.rb 文件中我没有注释:

config.token_authentication_key = :auth_token

我的用户迁移如下所示:

class DeviseCreateUsers < ActiveRecord::Migration
  def self.up
   create_table(:users) do |t|
    t.database_authenticatable :null => false
    t.recoverable
    t.rememberable
    t.trackable
    t.token_authenticatable
    t.timestamps
   end

   add_index :users, :email,                :unique => true
   add_index :users, :reset_password_token, :unique => true
   add_index :users, :authentication_token, :unique => true
  end

  def self.down
   drop_table :users
  end
end

创建用户时,会出现以下参数

{"utf8"=>"✓",
 "authenticity_token"=>"+F8cjCoauVKhZPSJLhW+AAhui1DygBcODsYn4Va/ktY=",
 "user"=>{"first_name"=>"any_name",
 "last_name"=>"any_name",
 "email"=>"any_email@gmail.com",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "cell_phone"=>"any_number",
 "city"=>"some_city",
 "state"=>"some_state",
 "country"=>"U.S.A",
 "user_type"=>"student"},
 "commit"=>"Sign up"}

但在创建用户时仍然出现以下错误:

NameError in Devise::RegistrationsController#create

   undefined local variable or method `ensure_authentication_token' for #<User:0x007fd4448f7350>

我在这里做错了什么?

附:在我的 Gemfile 中,Devise gem 配置如下:

gem 'devise', :git => 'git://github.com/plataformatec/devise.git', :branch => 'master'

【问题讨论】:

  • 为什么模型中有before_save :ensure_authentication_token这一行?原理是什么?
  • 根据资源我发现它应该在用户类中。所以我一直保留在模型中。
  • 什么资源?我相信这是罪魁祸首,如果你删除它,错误就会消失,但问题是“有什么影响?”。
  • 我希望能够将 token_key 保存在 User 模型的 authentication_token 字段中。为此,我将使用此回调。这是执行此操作的常规方法,即使在我阅读的 Manning 出版的名为“Rails 3 in Action”的书中也提到了这一点。顺便说一句,如果我删除该错误显然会消失但工作已撤消。你可以在这里看到github.com/plataformatec/devise/blob/master/lib/devise/models/…,这个回调是做什么的。
  • 我现在明白了。确实很奇怪。在控制台User.new.methods.grep /ensure_authentication_token/中试试看方法是否确实存在。

标签: ruby-on-rails ruby-on-rails-3 authentication ruby-on-rails-3.1 devise


【解决方案1】:

对不起,这是我的错,我错过了一个逗号:)

devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, :validatable, #here
  :token_authenticatable

它现在可以工作了。

【讨论】:

  • 大声笑。我遇到了同样的问题。非常感谢。
  • 大声笑!我知道,有时您会遇到这样的小问题,并且无法在回溯中获得有关该错误的正确信息。我希望回溯对用户更友好、更智能。但无论如何,我很高兴你发现了故障。 ;)
  • 我简直不敢相信我也发生了同样的事情。
猜你喜欢
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多