Rails 5 - 新必填模型字段的 Pundit 政策

Rails 5 - Pundit policy for the new required model field

我想将一个 phone 用户字段更改为必填。当现有用户没有设置此字段(不必事先提供 phone 号码)时,它应该重定向到 user_edit 页面并在表单下方显示 Phone is required 消息。我正在使用 Pundit gem 进行授权:

class ApplicationController < ActionController::Base
  include Pundit

  rescue_from Pundit::NotAuthorizedError, with: :login_not_authorized

  private

  def login_not_authorized
    flash[:alert] = 'You are not authorized to perform this action.'
    redirect_to(request.referer || root_path)
  end
end

如何检查现有用户是否有 phone 号码,如果没有则将此用户移动到他的编辑页面并在表单下方显示 Phone is required 错误消息?

你可以尝试使用这样的东西:

def login_not_authorized
  if current_user&.phone.blank?
    flash[:alert] = 'You must provide your phone number.'
    redirect_to(user_edit_path)
  else
    flash[:alert] = 'You are not authorized to perform this action.'
    redirect_to(request.referer || root_path)
  end
end