无法更新用户的 is_active 状态:user.update(is_active: true) 失败

huangapple go评论60阅读模式
英文:

Can't update is_active on user: user.update(is_active: true) fails

问题

user.update(is_active: true)在Rails控制台中有效,但在应用程序中无效。

这是来自sessions_controller.rb的代码:

def create
  username_or_email = params[:session][:username_or_email].downcase
  user = if username_or_email.include?("@")
    User.find_by(email: username_or_email)
  else
    User.find_by(username: username_or_email)
  end
  if user && user.authenticate(params[:session][:password])
    session[:user_id] = user.id 
    user.update!(is_active: true)
    redirect_to user_path(user.username)
  else
    flash.now[:danger] = 'Invalid email/password combination'
    render 'sign_in'
  end
end

我得到以下结果:
Validation failed: Password can't be blank, Password is too short (minimum is 6 characters)

这似乎很奇怪,密码也应该传递吗?

英文:

user.update(is_active: true) works in the rails console, but not in the application.

This is from the sessions_controller.rb:

  def create
    username_or_email = params[:session][:username_or_email].downcase
    user = if username_or_email.include?("@")
      User.find_by(email: username_or_email)
    else
      User.find_by(username: username_or_email)
    end
    if user && user.authenticate(params[:session][:password])
      session[:user_id] = user.id 
      user.update!(is_active: true)
      redirect_to user_path(user.username)
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'sign_in'
    end
  end

I get this result:
Validation failed: Password can't be blank, Password is too short (minimum is 6 characters)

Which seems strange, is the password supposed to be passed too?

答案1

得分: 0

解决方案是使用 update_columns 而不是绕过验证。
这是因为用户模型有以下验证:

validates :password, presence: true, length: { minimum: 6 }

我在用户模型中添加了 sign_insign_out 函数,并在这些函数中正确处理了它。

英文:

The solution was to bypass validation using update_columns instead.
This was because the user model had this validation:

validates :password, presence: true, length: { minimum: 6 }

I added sign_in and sign_out functions to the user model and handled it properly in those.

huangapple
  • 本文由 发表于 2023年2月8日 13:26:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定