34

I would like to manually create new Users, without forcing them to verify their email address.

The idea is to allow existing users to automatically add their friends without requiring their registration. It makes sense for the business case I'm working to solve.

How can this be achieved with Devise?

James
  • 5,273
  • 10
  • 51
  • 76
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

2 Answers2

50

The skip_confirmation! method is available to any confirmable model.

@user = User.new params[:user]
@user.skip_confirmation! # Sets confirmed_at to Time.now, activating the account
@user.save

The user account will be activated though. If you don't want that, continue reading.

Devise uses conditional callbacks to generate the confirmation token and send the email. The callbacks will be called only if confirmation_required? returns true. Redefine it on your model:

def confirmation_required?
  false
end

However, this will make the active_for_authentication? method always return true because it takes whether or not confirmation is required into account. We have to redefine that as well:

def active_for_authentication?
  confirmed? || confirmation_period_valid?
end

This way, the account will stay inactive and no confirmation email will be sent. You will have to manually activate the user by calling confirm! on the record or just setting confirmed_at to any date.

It's quite a hack, but it should work.

For reference: confirmable.rb

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
  • 1
    thank you. but I don't want the user to be able to log-in. will setting the user to confirmed allow the user to some how login? what will that do, just prevent emails from being sent? thanks – AnApprentice Jan 04 '11 at 23:37
  • Also, when I try to save a new user like you mentioned above i get FALSE on @user.save.... besides an email, what other fields are required to save a user? – AnApprentice Jan 05 '11 at 00:18
  • I updated my answer. Any fields that are marked as not null on your schema or whose presence your model validates for are required. If you don't provide them Active Record will not save your object. – Matheus Moreira Jan 05 '11 at 00:38
  • 2
    If you want to create a user only with email address, then you can deactivate the validation by u.save(:validate => false) – Bachet Nov 01 '11 at 11:39
  • 2
    active? is renamed to active_for_authentication? (from devise version 1.2.0) – santuxus Jan 12 '12 at 16:51
9

I just want to add for future reference that since Devise 2.2 there is now a skip_confirmation_notification! method available as well which basically does everything from Matheus' post without redefining the methods in the model.

UnSandpiper
  • 526
  • 6
  • 8