<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Pedro Leonardo</title>
    <description>The latest articles on DEV Community by Pedro Leonardo (@pedroleo).</description>
    <link>https://dev.to/pedroleo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2046885%2Fb81ee4ae-c43c-431b-85c6-0b6c159e4860.jpg</url>
      <title>DEV Community: Pedro Leonardo</title>
      <link>https://dev.to/pedroleo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/pedroleo"/>
    <language>en</language>
    <item>
      <title>Associações polimórficas no Rails: como fazer, prós e contras</title>
      <dc:creator>Pedro Leonardo</dc:creator>
      <pubDate>Tue, 16 Sep 2025 21:54:03 +0000</pubDate>
      <link>https://dev.to/pedroleo/associacoes-polimorficas-no-rails-como-fazer-pros-e-contras-450m</link>
      <guid>https://dev.to/pedroleo/associacoes-polimorficas-no-rails-como-fazer-pros-e-contras-450m</guid>
      <description>&lt;p&gt;Recentemente, me deparei com uma situação no trabalho em que precisava implementar uma tabela que se relacionasse com &lt;strong&gt;várias outras tabelas diferentes&lt;/strong&gt;, mas que possuía os mesmos campos em comum. Pesquisando sobre a melhor forma de lidar com isso no &lt;strong&gt;Rails&lt;/strong&gt;, descobri as &lt;a href="https://guides.rubyonrails.org/association_basics.html#polymorphic-associations" rel="noopener noreferrer"&gt;associações polimórficas&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Neste artigo, vamos aprender na prática como implementá-las e discutir suas &lt;strong&gt;vantagens, desvantagens e quando usar&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  O que são associações polimórficas?
&lt;/h2&gt;

&lt;p&gt;Uma &lt;strong&gt;associação polimórfica&lt;/strong&gt; é um recurso do Rails que permite que um mesmo modelo pertença a mais de um outro modelo, usando uma estrutura genérica.&lt;/p&gt;

&lt;p&gt;Por exemplo, imagine que você tenha um sistema em que &lt;strong&gt;usuários e empresas&lt;/strong&gt; podem ter &lt;strong&gt;contatos&lt;/strong&gt; (e-mail, telefone). Em vez de criar duas tabelas (&lt;code&gt;user_contacts&lt;/code&gt; e &lt;code&gt;company_contacts&lt;/code&gt;), você pode ter uma tabela única de &lt;code&gt;contacts&lt;/code&gt; que se relaciona com ambos.&lt;/p&gt;

&lt;h2&gt;
  
  
  Criando a associação polimórfica
&lt;/h2&gt;

&lt;p&gt;Implementar uma associação polimórfica no Rails é simples. Vamos criar uma tabela &lt;code&gt;contacts&lt;/code&gt; que poderá se relacionar tanto com &lt;code&gt;users&lt;/code&gt; quanto com &lt;code&gt;companies&lt;/code&gt; (ou qualquer outro modelo que precise de contatos).&lt;/p&gt;

&lt;h3&gt;
  
  
  Migration
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CreateContacts &amp;lt; ActiveRecord::Migration[7.1]
  def change
    create_table :contacts do |t|
      t.string :email
      t.string :phone

      t.references :contactable, polymorphic: true, null: false

      t.timestamps
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;O &lt;code&gt;t.references :contactable, polymorphic: true&lt;/code&gt; cria duas colunas:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;contactable_id&lt;/code&gt; (inteiro)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;contactable_type&lt;/code&gt; (string)&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;Esses dois campos indicam quem é o dono do contato.&lt;/p&gt;

&lt;h3&gt;
  
  
  Models
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Contact &amp;lt; ApplicationRecord
  belongs_to :contactable, polymorphic: true
end

class User &amp;lt; ApplicationRecord
  has_many :contacts, as: :contactable
end

class Company &amp;lt; ApplicationRecord
  has_many :contacts, as: :contactable
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Agora, tanto &lt;code&gt;User&lt;/code&gt; quanto &lt;code&gt;Company&lt;/code&gt; podem ter múltiplos contatos.&lt;/p&gt;

&lt;h3&gt;
  
  
  Exemplo de uso
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user = User.create(name: "Pedro")
company = Company.create(name: "ABC")

user.contacts.create(email: "pedro@email.com", phone: "1111-1111")
company.contacts.create(email: "contato@tech.com", phone: "2222-2222")

puts user.contacts.first.email     # =&amp;gt; "pedro@email.com"
puts company.contacts.first.phone  # =&amp;gt; "2222-2222"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Com isso, conseguimos reutilizar a tabela &lt;code&gt;contacts&lt;/code&gt; em diferentes contextos.&lt;/p&gt;

&lt;h2&gt;
  
  
  Vantagens
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Reutilização&lt;/strong&gt;: você cria &lt;strong&gt;uma única tabela&lt;/strong&gt; para relacionar com vários modelos diferentes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Menos duplicação&lt;/strong&gt;: evita criar várias tabelas para armazenar dados semelhantes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Flexibilidade&lt;/strong&gt;: se amanhã surgir outro modelo que precise de contatos (ex: &lt;code&gt;Suppliers&lt;/code&gt;), basta adicionar a associação.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Integração Rails&lt;/strong&gt;: o suporte nativo facilita bastante, sem precisar reinventar a roda.&lt;/p&gt;

&lt;h2&gt;
  
  
  Desvantagens
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Consultas mais complexas&lt;/strong&gt;: filtrar dados polimórficos pode gerar queries mais pesadas.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dificuldade em manter integridade&lt;/strong&gt;: o Rails não cria &lt;em&gt;foreign keys&lt;/em&gt; em colunas polimórficas (já que o campo pode apontar para várias tabelas diferentes).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Escalabilidade&lt;/strong&gt;: se a tabela crescer demais com dados de muitos modelos, pode virar um gargalo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Legibilidade&lt;/strong&gt;: para quem não conhece o conceito, entender o &lt;code&gt;contactable_type&lt;/code&gt; pode ser confuso.&lt;/p&gt;

&lt;h2&gt;
  
  
  Quando usar?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use quando&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Você tem dados &lt;strong&gt;idênticos&lt;/strong&gt; que precisam estar disponíveis em &lt;strong&gt;múltiplos modelos&lt;/strong&gt; (ex: contatos, endereços, imagens, comentários).&lt;/li&gt;
&lt;li&gt;A estrutura se repete bastante e faria pouco sentido criar tabelas separadas.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Evite quando&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Os dados variam muito entre os modelos (ex: se contatos de &lt;code&gt;User&lt;/code&gt; e &lt;code&gt;Company&lt;/code&gt; tivessem campos completamente diferentes).&lt;/li&gt;
&lt;li&gt;Você precisa de &lt;strong&gt;restrições fortes no banco&lt;/strong&gt; (integridade referencial por foreign keys diretas).&lt;/li&gt;
&lt;li&gt;A tabela polimórfica tende a crescer demais, impactando performance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Alternativa às associações polimórficas
&lt;/h2&gt;

&lt;p&gt;Uma alternativa às associações polimórficas é criar os relacionamentos de forma &lt;strong&gt;explícita&lt;/strong&gt; na tabela, adicionando colunas específicas como &lt;code&gt;user_id&lt;/code&gt;, &lt;code&gt;company_id&lt;/code&gt;, &lt;code&gt;supplier_id&lt;/code&gt;, etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  Exemplo de migration sem polimorfismo:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CreateContacts &amp;lt; ActiveRecord::Migration[7.1]
  def change
    create_table :contacts do |t|
      t.string :email
      t.string :phone

      # Relacionamentos explícitos
      t.references :user, foreign_key: true
      t.references :company, foreign_key: true

      t.timestamps
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Prós dessa abordagem:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Performance melhor&lt;/strong&gt;: consultas são mais rápidas porque não dependem de um campo &lt;code&gt;type&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Integridade no banco&lt;/strong&gt;: você consegue usar &lt;strong&gt;foreign keys&lt;/strong&gt; diretamente, garantindo consistência.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Legibilidade&lt;/strong&gt;: é mais fácil entender a relação olhando apenas a tabela.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Contras dessa abordagem:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pouca escalabilidade&lt;/strong&gt;: se amanhã surgir outro modelo (ex: &lt;code&gt;Supplier&lt;/code&gt;), você precisa &lt;strong&gt;alterar a tabela&lt;/strong&gt; e adicionar mais colunas.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Duplicação estrutural&lt;/strong&gt;: quanto mais modelos diferentes, mais colunas redundantes terá na tabela.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Essa opção costuma ser escolhida em cenários onde &lt;strong&gt;performance é prioridade&lt;/strong&gt; e o número de modelos relacionados é previsível e limitado.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;Associações polimórficas são uma ferramenta poderosa no Rails. Elas trazem simplicidade e reuso quando bem aplicadas, mas podem gerar &lt;strong&gt;complexidade desnecessária&lt;/strong&gt; e até &lt;strong&gt;impactar performance&lt;/strong&gt; em cenários de alto volume de dados.&lt;/p&gt;

&lt;p&gt;Uma alternativa válida é criar &lt;strong&gt;referências explícitas&lt;/strong&gt; (&lt;code&gt;user_id&lt;/code&gt;, &lt;code&gt;company_id&lt;/code&gt;, etc.) em vez de usar o campo polimórfico. Essa abordagem melhora a performance e permite integridade via &lt;strong&gt;foreign keys&lt;/strong&gt;, mas perde em &lt;strong&gt;flexibilidade&lt;/strong&gt; e exige alterações na tabela sempre que surgir um novo modelo relacionado.&lt;/p&gt;

&lt;p&gt;No fim, não existe solução única:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Se você precisa de &lt;strong&gt;flexibilidade e reuso&lt;/strong&gt; → vá de &lt;strong&gt;associação polimórfica&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Se você precisa de &lt;strong&gt;performance e integridade forte no banco&lt;/strong&gt; → prefira &lt;strong&gt;chaves explícitas (&lt;code&gt;_id&lt;/code&gt;)&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A escolha depende do &lt;strong&gt;contexto e das prioridades do projeto&lt;/strong&gt;.&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>rails</category>
      <category>sql</category>
      <category>development</category>
    </item>
    <item>
      <title>Email Verification with Sent Codes in Ruby on Rails without Devise</title>
      <dc:creator>Pedro Leonardo</dc:creator>
      <pubDate>Wed, 12 Feb 2025 13:17:32 +0000</pubDate>
      <link>https://dev.to/pedroleo/email-verification-with-sent-codes-in-ruby-on-rails-without-devise-479a</link>
      <guid>https://dev.to/pedroleo/email-verification-with-sent-codes-in-ruby-on-rails-without-devise-479a</guid>
      <description>&lt;p&gt;Hello, we know that email verification is present in many applications in our daily lives. It is through it that we improve the sender's reputation and, most importantly, prevent identity forgery. Given this, I saw in the Rails community that using Devise is quite common, but what if you wanted to implement something from scratch? How would you do it? Today, I’m going to teach you.&lt;/p&gt;

&lt;p&gt;For this example, I will be using Rails 7.2, SQLite3, and Bcrypt.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Initial Configuration
&lt;/h2&gt;

&lt;p&gt;To create the Rails application, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rails new verification-app
cd verification-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.1 Create a Model for User&lt;/strong&gt;&lt;br&gt;
Run in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rails generate model User name:string email:string password_digest:string verification_code:string verified:boolean
rails db:migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Change &lt;code&gt;app/models/user.rb&lt;/code&gt; to include secure authentication:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User &amp;lt; ApplicationRecord
  has_secure_password
  before_create :generate_verification_code
  validates :name, :email, presence: true
  validates :email, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }

  def generate_verification_code
    self.verification_code = rand(100000..999999).to_s
    self.verified = false
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Method &lt;code&gt;generate_verification_code&lt;/code&gt;: This method generates a random verification code (a 6-digit number) whenever a new user is created. The code is stored in the &lt;code&gt;verification_code&lt;/code&gt; attribute, and the &lt;code&gt;verified&lt;/code&gt; attribute is set to &lt;code&gt;false&lt;/code&gt;, indicating that the user has not been verified yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Mailer Configuration
&lt;/h2&gt;

&lt;p&gt;The Mailer is the Rails module responsible for facilitating email sending. It allows you to define templates, layouts, and some logic for emails in an organized way.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.1 Creating Mailer&lt;/strong&gt;&lt;br&gt;
Run in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rails generate mailer UserMailer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Change &lt;code&gt;app/mailers/user_mailer.rb&lt;/code&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class UserMailer &amp;lt; ApplicationMailer
  default from: 'youremail@gmail.com'

  def verification_email(user)
    @user = user
    mail(to: @user.email, subject: "Verification Code")
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In '&lt;a href="mailto:youremail@gmail.com"&gt;youremail@gmail.com&lt;/a&gt;', use the email that will be responsible for sending to users. I recommend using it in a credential or environment variable, but in this example, I will make it very explicit.&lt;/p&gt;

&lt;p&gt;Create view &lt;code&gt;app/views/user_mailer/verification_email.html.erb&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;style&amp;gt;
    @import url('https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css');
  &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body class="bg-gray-100 font-sans leading-normal tracking-normal"&amp;gt;
  &amp;lt;div class="max-w-lg mx-auto my-10 bg-white p-8 rounded-lg shadow-lg"&amp;gt;
    &amp;lt;h1 class="text-2xl font-bold mb-4"&amp;gt;Verify your account&amp;lt;/h1&amp;gt;
    &amp;lt;p class="text-lg mb-4"&amp;gt;Hi, &amp;lt;%= @user.name %&amp;gt;!&amp;lt;/p&amp;gt;
    &amp;lt;p class="text-lg mb-4"&amp;gt;Your verification code is: &amp;lt;strong class="text-blue-500"&amp;gt;&amp;lt;%= @user.verification_code %&amp;gt;&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;
    &amp;lt;p class="text-lg"&amp;gt;Enter this code on the verification page to activate your account.&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This view will be the layout of the email that the user will receive. You can style it with Tailwind, as shown in the example. You can also use it in a regular erb structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.2  SMTP Configuration (Gmail - Tests)&lt;/strong&gt;&lt;br&gt;
In my application, I chose to use Gmail to send emails, but you can use other services, such as SendGrid (recommended for production). Just configure them according to each one's instructions.&lt;/p&gt;

&lt;p&gt;In the case of Gmail, you need to register an application at the following link and use the password it provides in your Rails Credentials or ENV, if you prefer.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Acess: &lt;a href="https://myaccount.google.com/apppasswords" rel="noopener noreferrer"&gt;https://myaccount.google.com/apppasswords&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Generate a password for your app and use it instead of your real password.&lt;/li&gt;
&lt;li&gt;In "user_name," it's the email that will be used.&lt;/li&gt;
&lt;li&gt;In "password," you will enter the password generated from the Gmail application registration.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Add in &lt;code&gt;config/environments/development.rb&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address: "smtp.gmail.com",
  port: 587,
  domain: "gmail.com",
  authentication: "plain",
  enable_starttls_auto: true,
  user_name: Rails.application.credentials.gmail_username,
  password: Rails.application.credentials.gmail_password
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. UsersController Implementation
&lt;/h2&gt;

&lt;p&gt;In our Controller, this is where the methods responsible for handling requests and implementing the logic for sending emails are located.&lt;br&gt;
Change &lt;code&gt;app/controllers/users_controller.rb&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class UsersController &amp;lt; ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      UserMailer.verification_email(@user).deliver_now
      redirect_to verify_user_path(@user), notice: "Code sent to your email."
    else
      render :new, status: :unprocessable_entity, notice: "Try again"
    end
  end

  def verify
    @user = User.find(params[:id])
  end

  def confirm_verification
    @user = User.find(params[:id])
    if @user.verification_code == params[:verification_code]
      @user.update(verified: true, verification_code: nil)
      redirect_to new_session_path, notice: "Account verified! Log in."
    else
      flash.now[:alert] = "Code invalid!"
      render :verify, status: :unprocessable_entity
    end
  end

  def resend_verification_code
    @user = User.find(params[:id])
    @user.update(verification_code: rand(100000..999999).to_s)
    UserMailer.verification_email(@user).deliver_now

    redirect_to verify_user_path(@user), notice: "New code sent to your email."
  end

  def show
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Create the Email Verification View.
&lt;/h2&gt;

&lt;p&gt;This will be our basic view where we can enter the code we receive in the email.&lt;br&gt;
Create &lt;code&gt;app/views/users/verify.html.erb&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="max-w-md mx-auto mt-10 p-6 bg-white shadow-lg rounded-lg"&amp;gt;
  &amp;lt;h1 class="text-2xl font-bold mb-4"&amp;gt;Verificação de Conta&amp;lt;/h1&amp;gt;

  &amp;lt;p class="mb-4"&amp;gt;A verification code has been sent to your email.&amp;lt;/p&amp;gt;

  &amp;lt;%= form_with url: confirm_verification_user_path(@user), local: true, class: "space-y-4" do |form| %&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;%= form.label :verification_code, "Enter the Code", class: "block text-sm font-medium text-gray-700" %&amp;gt;
      &amp;lt;%= form.text_field :verification_code, class: "mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" %&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;div&amp;gt;
      &amp;lt;%= form.submit "Verify Account", class: "w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" %&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;% end %&amp;gt;
  &amp;lt;p id="resend-info"&amp;gt;You can resend the code at &amp;lt;span id="timer"&amp;gt;30&amp;lt;/span&amp;gt; seconds.&amp;lt;/p&amp;gt;
  &amp;lt;%= button_to "Resend Code", resend_verification_code_user_path(@user), method: :post, id: "resend-button", disabled: true %&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;script&amp;gt;
  document.addEventListener("DOMContentLoaded", function() {
    let timer = 30;
    let button = document.getElementById("resend-button");
    let timerText = document.getElementById("timer");

    let countdown = setInterval(function() {
      timer--;
      timerText.textContent = timer;

      if (timer &amp;lt;= 0) {
        clearInterval(countdown);
        button.disabled = false;
        document.getElementById("resend-info").textContent = "Didn't receive the code? Resend now.";
      }
    }, 1000);
  });
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Routes configuration
&lt;/h2&gt;

&lt;p&gt;Lastly, the configuration of our routes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;resources :users, only: [:new, :create, :show] do
  member do
    get :verify
    post :confirm_verification
    post :resend_verification_code
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;And that's it, now you can send real emails. If it's just for local testing, Gmail works well. For production, SendGrid or Mailgun are more recommended. Rails is capable of doing countless things with numerous possibilities, and email sending is one of them with relative ease. I hope this article helps those who need it, and if you find something wrong or have a suggestion for improvement, feel free to leave it in the comments so we can discuss it.&lt;/p&gt;

&lt;p&gt;Repository in my Github: &lt;a href="https://github.com/pedrosrc/Rails-Verification-Email" rel="noopener noreferrer"&gt;Rails-Verification-Email&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>rails</category>
      <category>tutorial</category>
      <category>security</category>
    </item>
  </channel>
</rss>
