【问题标题】:Unable to create user using devise Rails无法使用设计 Rails 创建用户
【发布时间】:2015-09-11 04:58:31
【问题描述】:

我的代码:

class TestController < ApplicationController
  def testpage
    user = User.new(:email => 'test@sd.com', :encrypted_password => 'test')
    user.save
  end
end

我正在尝试从脚本内部手动保存用户,但它永远不会保存,但是我可以通过以下代码更新用户:

class TestController < ApplicationController
  def testpage
    user=User.find(2)
    user.update(:email => 'new', :encrypted_password => 'new')
  end
end

所以我的第二个代码工作正常,但不是第一个,我不知道为什么。 这是我的User 模型:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :manager
end

我不知道出了什么问题,我想拯救用户。我正在使用设计。 而且我也没有遇到任何错误。

编辑1: 在用 user.save 替换 user.save 时!我收到此错误。

验证失败:密码不能为空,密码确认 密码不匹配

【问题讨论】:

  • 试试这个:User.new(email: 'test@sd.com', password: 'test', password_confirmation: 'test')。这应该有效。
  • @Deep 没用,还有什么建议吗?
  • 您遇到的错误是什么?只需将user.save 替换为user.save!,看看是什么错误。
  • 验证失败:密码不能为空,密码确认与密码不匹配我有两个密码作为测试,但还是这个错误,奇怪...
  • 试试这个User.create!(email: 'test@sd.com', password: 'test', password_confirmation: 'test')

标签: ruby-on-rails devise


【解决方案1】:

您存储散列密码的列​​ encrypted_pa​​ssword 通常受到保护,不会被修改。相反,很少有访问者提供接口来设置密码和加密。

所以这就是你需要的:

class TestController < ApplicationController

  def create
    user = User.new
    user.email = 'new'
    user.password = user.password_confirmation = 'new'
    if user.valid?
      user.save
    else
      redirect_to :back
    end
  end


  def update
    user = User.find(2)
    if user
      user.email = 'new'
      user.password = user.password_confirmation = 'new'
      user.save
    end
  end
end

我抑制了错误和异常处理,因此请确保在部署之前涵盖这些情况。

【讨论】:

  • 我没有修改问题,就像我上面提到的那样工作正常,我在创建新用户时遇到问题。
  • 终于哇!电子邮件仍然必须经过验证且密码大于 8 个字符,并且有效!!!非常感谢,我已经为此工作了 10 个小时......
【解决方案2】:

或者你可以使用

user = User.create(email: 'test@sd.com', encrypted_password: 'test')

而不是

user = User.new(email:  'test@sd.com', encrypted_password:  'test')
user.save

【讨论】:

  • 没用,什么也没发生,我用上面的行替换了这两行,没有错误,也没有任何东西保存到数据库中(我使用的是 postgreSQL)。放在 user.save 上!在 user.create 之后,我得到了与我在 edit1 下的帖子中提到的相同的验证错误。
  • 我想我忘记了 User.create 之后的感叹号。还有一件事,如果您为设计启用了可确认模块,请在创建时将确认的_at 值设置为 Time.now。
  • 不,我没有使用可确认模块,因为您可以在上面看到我的用户模型,我已经发布了。我在创建后添加了感叹号,得到同样的错误:验证失败:密码不能为空,密码确认与密码不匹配,即使密码根本不为空
  • 这是我来自上一个项目“User.create!(email:"borshchov@ukr.net", password: "password")" 的 "seeds.rb" 的代码
  • 我为密码和密码确认输入了 8 个字符的密码,现在没有错误出现,但数据仍然没有从控制器保存,而是从 seed.rb 保存
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 2013-05-31
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多