Search code examples
ruby-on-railsrubypundit

Rails 5 - Pundit policy for the new required model field


I want to change one phone user field to be required. When the existing user does not have this field set (did not have to provide a phone number beforehand) it should redirect to the user_edit page and display Phone is required message below form. I'm using Pundit gem for authorization:

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

How to check if existing user have phone number and if not move this user to his EDIT page and display Phone is required error message below form?


Solution

  • You could try to use something like this:

    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