-
Notifications
You must be signed in to change notification settings - Fork 0
5. Bonus Content
Franco Pariani edited this page Aug 18, 2022
·
2 revisions
Rails provides a simple way to create and send mails.
Let's create a Mailer by running this command:
foo@bar:~$ rails g mailer User company_created
create app/mailers/user_mailer.rb
invoke erb
create app/views/user_mailer
invoke test_unit
create test/mailers/user_mailer_test.rb
create test/mailers/previews/user_mailer_preview.rbGo to the file app/mailers/user_mailer.rb and edit it like this:
class UserMailer < ApplicationMailer
def company_created(company, user)
@company = company
mail to: user.email
end
endNow, let's edit the template (app/views/user_mailer/company_created.html.erb)
<h1>Congrats!</h1>
<p>
Your company <%= @company.name %> has been created!
</p>Now, add the gem letter_opener:
gem "letter_opener", group: :developmentRun bundle install.
Then set the delivery method in config/environments/development.rb
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.perform_deliveries = trueRails provides different callbacks you can trigger after or before certain actions.
In order to trigger the previous email after company creation, we can add this to the Company model:
class Company < ApplicationRecord
...
after_create :send_company_created_email
private
def send_company_created_email
UserMailer.company_created(self, user).deliver_now
end
...
endCreate a new company and let the magic begin!