I have a basic application with a user model. When the user creates an account I would like to sent them an email. I originally had this setup in the controller itself.
if @user.save
UserMailer.welcome_email(@user, new_session_url).deliver
redirect_to root_url, notice: 'User was successfully created. Please check your email for more information'
This seemed fine to me at the time. I later learned about Observers in Rails. A common example of using an observer was to move this email logic above outside of the controller and into a “user observer”. This seemed like a great idea.
I immediately ran into 2 major problems:
- My observer cannot access new_session_url. I really want to be able to include in my email to the user a link back to the login page. I am shocked to see so many examples of using an observer for this, without touching on this issue.
- My observer has no access to flash messages. It can’t notify the user that an email was sent.
My question is this. Should I be trying to use an observer here. Its starting to look like I would have a much easier time using callbacks for this directly in the controller. If this is not an appropriate use case for an observer than what is? This situation seems to be one of the primary examples of using an observer.
You dont have to access the session-url(even flash) in the observer.
You just have to call the method like this:
Controller
Observer:
You have to use the session-url in the actual view:
welcome_email.html.erb
In this way we can test the email logic separately. Also if there are multiple entry points for creating an user, you dont have to replicate the logic everywhere.