【发布时间】:2013-11-27 19:03:12
【问题描述】:
我正在修改 Rails 应用程序以使用“has_secure_password”,但这导致了意外问题。
当用户创建帐户时,他们指定姓名、电子邮件、密码、密码确认,并允许选择零个或多个朋友(见下面的屏幕截图)。
在我的控制器中,我在保存新用户实体的同时创建友谊关联。这是通过使用关联用户对象数组填充创建参数的“朋友”属性来完成的。
def create
checked_params = user_params
if checked_params[:friends]
checked_params[:friends].delete ""
checked_params[:friends] = checked_params[:friends].map { |id| User.find(id) }
end
@user = User.new(checked_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: @user }
else
@friends = user_params[:friends] # Replace with simple names and IDs
format.html { render action: 'new' }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
这种方法曾经有效,直到将“has_secure_password”添加到我的用户模型中。现在,每当我保存我的模型时,我都会收到一条通用的“朋友无效”消息。即使知道此消息来自何处也会有所帮助。
我的项目是hosted on GitHub
这里是我为了打破我的朋友储蓄而必须进行的唯一更改的差异。
diff --git a/Gemfile b/Gemfile
index 9beb2e3..2905724 100644
--- a/Gemfile
+++ b/Gemfile
@@ -36,7 +36,7 @@ group :doc do
# Use ActiveModel has_secure_password
-# gem 'bcrypt-ruby', '~> 3.0.0'
+ gem 'bcrypt-ruby', '~> 3.0.0'
diff --git a/app/models/user.rb b/app/models/user.rb
index b5e6674..6d9cec9 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -23,5 +23,6 @@ class User < ActiveRecord::Base
- validates_confirmation_of :password
+
+ has_secure_password
diff --git a/db/migrate/20131018155801_create_users.rb b/db/migrate/201310181558
index 3b4a508..2a8cd85 100644
--- a/db/migrate/20131018155801_create_users.rb
+++ b/db/migrate/20131018155801_create_users.rb
@@ -3,7 +3,7 @@ class CreateUsers < ActiveRecord::Migration
create_table :users do |t|
t.string :name, null: false
t.string :email, null: false
- t.string :password, null: false
+ t.string :password_digest, null: false
t.string :role, null: false
t.timestamps
【问题讨论】:
-
问题很简单,在我的验证中,我验证了:password,presence:true 这是在 has_secure_password 中执行的验证的副本。不知道为什么这会导致我看到的意外行为,但删除我的验证解决了这些症状。
标签: ruby-on-rails ruby-on-rails-4