lss
lss

Reputation: 1325

Rails always redirect to edit page if email is empty

I have a Ruby on Rails web application, where a user needs to provide his nickname and password to register. After successful registration, the user is redirected to an edit page, where he should enter his email.

The use case requires to always redirect the user to the edit page until he has submitted a valid email address. However, in the current state, the user can click on any menu item and is then taken to the corresponding page. How do I prevent this behavior and redirect the user back to the edit page when clicking on a menu link?

Upvotes: 1

Views: 90

Answers (2)

Tamer Shlash
Tamer Shlash

Reputation: 9523

You can create a before_action in your ApplicationController which checks if the user is logged in and has submitted his email, something like this:

class ApplicationController < ActionController::Base
  before_action :validate_email_confirmed

  def validate_email_confirmed
    return unless current_user
    redirect_to user_edit_path unless current_user.email?
  end
end

Keep in mind that you have to skip this before_action for both the user edit and update actions, or you'll end up having a redirect loop. This is how to skip an existing before_action for specific actions:

class UsersController < ApplicationController
  skip_before_action :validate_email_confirmed, only: [:edit, :update]
end

Upvotes: 2

Fredrik
Fredrik

Reputation: 1031

Did some more digging, and found this on the official docs, seems to fit your needs:

class ApplicationController < ActionController::Base
  before_action LoginFilter
end

class LoginFilter
  def self.before(controller)
    unless controller.send(:logged_in?)
      controller.flash[:error] = "You must be logged in to access this section"
      controller.redirect_to controller.new_login_url
    end
  end
end

You'd of course have to rework this some, to get awaiting_email or such, but the principle is the same.

Upvotes: 1

Related Questions