has_secure_password打破集合保存

时间:2013-11-27 19:03:13

标签: ruby-on-rails ruby-on-rails-4

我正在修改Rails应用程序以使用'has_secure_password',但这会导致意外问题。

当用户创建帐户时,他们会指定姓名,电子邮件,密码,password_confirmation,并且可以选择零个或多个朋友(请参阅下面的屏幕截图)。

Screenshot of User Add Form

在我的控制器中,我在保存新用户实体的同时创建了友谊关联。这是通过使用关联用户对象数组填充创建参数的'friends'属性来完成的。

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”添加到我的用户模型。现在,每当我保存模型时,我都会收到一个通用的“Friends is invalid”消息。即使知道这条消息的来源也会有所帮助。

我的项目是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

1 个答案:

答案 0 :(得分:0)

问题只是在我的验证中我有

validates :password, presence: true

这是在has_secure_password中执行的验证的副本。 不知道为什么这会导致我看到的意外行为,但删除我的重复验证解决了症状。

相关问题