Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Devise: Sending a reset password link as part of a welcome email

#devise #rails #technical

Occasionally you’d need to have a user who’s not registered preform an action and only enter their email address the result of which creates an account. For example when you want to get the user up and running as soon as possible without having to go through the entire set up of creating an account separately. As a result you’d need to have the user set up their password on the first login.

That can be achieved by using the Devise reset password link and a welcome email.

#in app/models/user.rb

  # After creating the user push the task to a background job (DelayedJob or Sidekiq for example)
  after_create do
    User.delay.welcome(self.id)
  end

  def welcome(id)
    user = User.find(id)
    @raw = nil
    raw, enc = Devise.token_generator.generate(user.class, :reset_password_token)

    user.reset_password_token   = enc
    user.reset_password_sent_at = Time.now.utc
    user.save(validate: false)
    @raw = raw

    UsersMailer.welcome(user, @raw).deliver_now
  end
#in app/views/users_mailer/welcome.html.erb

  <%= link_to 'Login here', edit_user_password_url(reset_password_token: @raw)%>