【问题标题】:ActiveModel::SecurePassword undefined method `password_digest='ActiveModel::SecurePassword 未定义方法 `password_digest='
【发布时间】:2023-04-01 00:36:01
【问题描述】:

我尝试通过关注 http://bcardarella.com/post/4668842452/exploring-rails-3-1-activemodel-securepassword 来使用 rails 3.1 ActiveModel::SecurePassword

我最终会闯红灯......

用户.rb

class User < ActiveRecord::Base
  has_secure_password
  validates :password, :presence => { :on => :create }
end

工厂.rb

Factory.define :user do |f|
  f.email "foo@bar.com"
  f.password "foobar"
  f.password_confirmation { |u| u.password }  
end

spec_user.rb

describe User do
  it "should authenticate with matching username and password" do
    user = Factory(:user, :email => 'frank@gmail.com', :password => 'secret')
    User.authenticate('frank@gmail.com', 'secret').should == user
  end
end

我得到一个红灯...

 Failure/Error: user = Factory(:user, :email => 'frank@gmail.com', :password => 'secret')
 NoMethodError:
   undefined method `password_digest=' for #<User:0xb383460>

我认为这是 rake db:migrate 问题,我查看了 rails c ,但显然 password_digest 已定义。

ruby-1.9.2-p180 :007 > a = User.new
 => #<User id: nil, email: nil, password_digest: nil, is_admin: nil, created_at: nil, updated_at: nil> 
ruby-1.9.2-p180 :008 > a.password_digest = 3
 => 3 

【问题讨论】:

    标签: ruby-on-rails authentication activerecord ruby-on-rails-3.1 activemodel


    【解决方案1】:

    我遇到了同样的问题,并在以下评论中找到了一个(我认为是)更好的解决方案:

    http://bcardarella.com/post/4668842452/exploring-rails-3-1-activemodel-securepassword#comment-281584959

    基本上,您需要通过迁移将 password_digest 字段添加到您的模型中。在此之前,它会添加一个password_digest=方法,但它不会被保存,并且该方法不会出现在工厂等中

    【讨论】:

      【解决方案2】:

      解决了

      describe User do
        it "should authenticate with matching username and password" do
          user = Factory(:user, :email => 'frank@gmail.com', :password => 'secret')
          User.find_by_email('frank@gmail.com').try(:authenticate, 'secret').should == user
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2018-06-16
        • 2018-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多