【问题标题】:Password doesn't get updated for user in rails after reseting重置后不会为 Rails 中的用户更新密码
【发布时间】:2019-09-16 18:14:12
【问题描述】:

我之前有一个页面作为设置来更新 Rails 中的用户详细信息。那时密码更新没有任何问题。但是现在我为忘记密码的用户使用了密码重置选项。他们将收到一封邮件,然后他们重置密码。添加此功能后,帐户内部和通过邮件的更新都不会发生。

密码重置控制器:

def update

  @user = User.find_by_password_reset_token!(params[:id])
  if @user.password_reset_sent_at < 2.hour.ago
    flash[:notice] = 'Password reset has expired'

    redirect_to new_password_reset_path

  elsif @user.update_attributes(params[:user])// this condition fails. I don't know why it fails.

    flash[:notice] = 'Password has been reset!'
    redirect_to new_session_path
  else
   redirect_to new_session_path
  end

用户.rb

  validates :password, presence: true, length: { minimum: 6 } 
  validates :password_confirmation, presence: true 
  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token


  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end

    def generate_token(column)
      begin
        self[column] = SecureRandom.urlsafe_base64
      end while User.exists?(column => self[column])
    end

我在用户控制器中使用的这些过滤器

 before_filter :signed_in_user, only: [:edit, :update, :requestuser]
 before_filter :correct_user,   only: [:edit, :update]
 before_filter :admin_user,     only: :destroy

我是 Rails 和学习新手。需要帮忙。我在密码重置之前使用的相同过滤器我不知道它为什么会失败。它最初工作了几天,现在失败了。

【问题讨论】:

  • 您的 cmets 在代码中显示“此条件失败”。请显示错误的堆栈跟踪。
  • 您用ruby-on-rails-3 标记了您的问题。你真的在使用三年多前报废的 Rails 3.x 吗?

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

您编写了条件,但我认为您的第二个条件设置不正确,分别在您的情况下,elsif 不包含任何条件。

if 语句的正确语法是

if conditional
   code
elsif conditional
   code
else
   code
end

条件是 if 语句和比较运算符(、=、==、!=、&&、||)的组合。

如果您牢记条件并重新访问您的代码,则缺少条件,我希望看到类似的东西,看看 if 和 elsif,我已经交换了 > 和

@user = User.find_by_password_reset_token!(params[:id])
if @user.password_reset_sent_at > 2.hour.ago
  # your if action here ...

elsif @user.password_reset_sent_at < 2.hour.ago
  @user.update_attributes(params[:user])

else
  # your else action ...
end

要知道在使用update_attributes 时出现静默错误或返回错误值时发生了什么,我建议使用update_attributes!(attributes),至少用于测试/调试。此方法也像 Base.update_attributes 一样更新对象,但调用 save!而不是保存,因此如果记录无效并且您可以看到发生了什么问题,则会引发异常。

您还可以通过在终端中键入 rails c 并在其中测试 @user.update_attributes('any_value') 来使用 Rails 控制台。

【讨论】:

  • 这大概就是我刚刚输入的内容,我认为这是个好建议。除此之外,还可以在不使用 update_attributes 方法的情况下分配密码,这是可以尝试的。它看起来有点像@user.password = params[:user][:password],然后if @user.save 在它下面做点什么。
  • @user.save 失败我不知道为什么
  • 您修复了条件还是只是您的问题中的拼写错误?如果失败,请尝试user.save! 引发错误。同样适用于update_attributes!(attributes),这也像 Base.update_attributes 一样更新对象,但调用保存!而不是保存,因此如果记录无效,则会引发异常。
  • 更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多