ruby-on-railscontrollerauthorizationmailer

Confirm user before create


In my application I currently have the ability to create a user which then begins a session and sends an email confirmation to the email address. Whilst this is all good I wish to make it a little more advanced.

What I wish to do is to have the ability of created the user and then the email gets sent that requires the user to verify through the email. Once they click confirmation link in the email the user is then registered to the database and then is able to log in. I want this link to go to the create function.

How would I go about doing so?

If my current code is needed then I can provide.

I have this in my controller/create at the moment:

def create @user = User.new(params[:user])

respond_to do |format|
  if @user.save
    Notifier.user_created(@user).deliver
    session[:user_id] = @user.id
    format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render json: @user, status: :created, location: @user }
  else
    format.html { render action: "new" }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end
end

Solution

  • Waiting to save the user to the database is a nearly impossible thing to do with the stateless manner that the web operates in, however, that doesn't mean it can't be done.

    I'd recommend using an extra field in your user table, called something like confirmed. Have it initialize to false, and then have the confirmation form simply look up the user and change confirmed to true.

    This will allow you quickly tell if a user has confirmed themselves and you can use it to make decisions like whether or not they are allowed to log in.

    In terms of people who never confirm themeselves, you write a rake task that ran every 5 days or so and just delete any users that have yet to confirm themselves, using something like resque_scheduler or a cron job.

    Hope this is a start to your solution.