Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a welcome email to newly registered users in Rails using Devise?

I am using Devise on Rails and I'm wondering if there is a hook or a filter that I can use to add a bit of code to Devise's user registration process and send a welcome email to the user after an account has been created. Without Devise it would be something like this...

  respond_to do |format|
      if @user.save
        Notifier.welcome_email(@user).deliver    # <======= 
  ...   
like image 299
picardo Avatar asked Nov 10 '10 01:11

picardo


2 Answers

The next most popular answer assumes you're using using Devise's :confirmable module, which I'm not.

I didn't like the other solutions because you have to use model callbacks, which will always send welcome emails even when you create his account in the console or an admin interface. My app involves the ability to mass-import users from a CSV file. I don't want my app sending a surprise email to all 3000 of them one by one, but I do want users who create their own account to get a welcome email. The solution:

1) Override Devise's Registrations controller:

#registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController

  def create
    super
    UserMailer.welcome(resource).deliver unless resource.invalid?
  end

end

2) Tell Devise you overrode its Registrations controller:

# routes.rb
devise_for :users, controllers: { registrations: "registrations" }
like image 178
Arcolye Avatar answered Oct 16 '22 01:10

Arcolye


https://stackoverflow.com/a/6133991/109618 shows a decent (not perfect) answer, but at least better than ones I'm seeing here. It overrides the confirm! method:

class User < ActiveRecord::Base
  devise # ...
  # ...
  def confirm!
    welcome_message # define this method as needed
    super
  end
  # ...
end

This is better because it does not use callbacks. Callbacks are not great to the extent that they (1) make models hard to test; (2) put too much logic into models. Overusing them often means you have behavior in a model that belongs elsewhere. For more discussion on this, see: Pros and cons of using callbacks for domain logic in Rails.

The above approach ties into the confirm! method, which is preferable to a callback for this example. Like a callback though, the logic is still in the model. :( So I don't find the approach fully satisfactory.

like image 10
David J. Avatar answered Oct 16 '22 01:10

David J.