我在 Rails 控制台中遇到了错误。我正在使用最新版本的 Rails 和 Pry。我正在尝试生成用户。我可以在用户属性中设置值,但无法保存它们。也许 User.new 在某个地方循环?这是我的模型的属性相关代码:
require 'bcrypt'
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :description, :profile_photo, :password, :password_confirmation, :email
attr_reader :password
has_secure_password
validates_presence_of :email, :session_token, :first_name, :last_name, :password_digest
validates_uniqueness_of :email
validates :password, length: { minimum: 6, maximum: 20 }
before_validation :reset_session_token!, on: :create
before_save :encrypt_new_password
这是我的用户迁移:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email, unique: true, null: false
t.string :password_digest, null: false
t.string :first_name, null: false
t.string :last_name, null: false
t.string :description, limit: 400
t.string :session_token, null: false
t.attachment :profile_photo
t.integer :profile_photo_id
t.datetime :profile_photo_updated_at
t.timestamps
end
add_index :users, :email
add_index :users, :first_name
add_index :users, :last_name
add_index :users, :session_token
add_index :users, :created_at
end
end
在尝试通过User.new(values)然后.save或User.create(values)或u = User.new然后u.value = value然后u.save创建用户后,这是我的 Rails 控制台错误。
[10] pry(User):1> u.save
(0.2ms) BEGIN
(0.2ms) ROLLBACK
SystemStackError: stack level too deep
from /Users/joecase/.rvm/gems/ruby-2.1.0/gems/pry-0.9.12.6/lib/pry/pry_instance.rb:328
[11] pry(User):1> u.errors
=> #<ActiveModel::Errors:0x0000010527ccb0
@base=
#<User id: nil, email: "joecase@nyu.edu", password_digest: "111111", first_name: "Joe", last_name: "Case", description: nil, session_token: "CVnrsyyTwoOp9TZkqmVfTw", profile_photo_file_name: nil, profile_photo_content_type: nil, profile_photo_file_size: nil, profile_photo_updated_at: nil, profile_photo_id: nil, created_at: nil, updated_at: nil>,
@messages={}>
[12] pry(User):1> u.errors.full_messages
=> []
任何帮助,将不胜感激。先感谢您。
加密新密码:
def encrypt_new_password
return if password.blank?
self.hashed_password = encrypt(password)
end
重置会话令牌:
def reset_session_token
self.session_token ||= SecureRandom.urlsafe_base64(16)
save!
end