psharma
psharma

Reputation: 1289

Send a welcome email after the user has confirmed his account

I am using devise and actionmailer. I am wondering how do I trigger an actionmailer method after the user has confirmed his account on the app and not before This actionmailer method is nothing but a welcome message.

Also, how do I fetch that sames users info, like name or email? I tried resource. But it didn't work.

Upvotes: 2

Views: 3063

Answers (5)

Mitch Nick
Mitch Nick

Reputation: 302

Devise has a built in callback for this scenario.

    # A callback initiated after successfully confirming. This can be
    # used to insert your own logic that is only run after the user successfully
    # confirms.
    #
    # Example:
    #
    #   def after_confirmation
    #     self.update_attribute(:invite_code, nil)
    #   end
    #
    def after_confirmation
    end

You can find the code in devise/lib/devise/models/confirmable.rb

Upvotes: 1

coderhs
coderhs

Reputation: 4827

Using after_save would make your application run and check the condition whether the user was confirmed just now. That would lead to an unnecessary delay.

I recommend overriding the default confirm function provided by devise using the following code.

class User < ActiveRecord::Base
  devise :invitable, :database_authenticatable, :registerable, :recoverable, 
         :rememberable, :confirmable, :validatable, :encryptable

  # Override devise confirm! message
  def confirm!
    welcome_email
    super
  end

  # ...

private

  def welcome_email
    UserMailer.welcome_message(self).deliver
  end

end

http://csnipp.com/s/507/-Send-welcome-mail-after-confirmation-devise

Upvotes: 0

Granville Schmidt
Granville Schmidt

Reputation: 399

This is actually a relatively easy task. All you need to do is create an Observer for your User class.

class UserObserver < ActiveRecord::Observer
    def after_save(user)            
        if user.confirmed_at_changed?
            #send email
        end
    end
end

Upvotes: 2

psharma
psharma

Reputation: 1289

This did it.

after_save :send_welcome_email
  def send_welcome_email
    WelcomeEmail.notify(self).deliver if self.confirmed_at_changed?
  end

Upvotes: 1

changey
changey

Reputation: 19576

Rails 3: Send welcome e-mail using Devise has a good answer you can do something like

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

Upvotes: 1

Related Questions