DIY lead collection form

Ruby on Rails Marketing

You don't always need to rely on third-party services to get things done. In many cases, using a combination of over the counter tools and custom solutions can simplify your processes. Let's build a form so you can start capturing leads straight into your Rails app!

A subscription form I made A form I had to make to quickly start capturing leads

Creating a form to collect leads in a Ruby on Rails application is a common task and can be worthwhile. It'll give you :

  • Full Control over the data collected and how it's stored.
  • Customization for your form and the entire lead collection process to match your brand and requirements.
  • Data Ownership. With third-party services your data is stored on their servers.
  • No Additional Costs:

Plus it's quite easy! You can do this in your Rails application by following the steps below. We'll be adding a lead collection form in our homepage :

1. Generate a Leads model

rails generate model Lead email:string unsubscribed_at:datetime
rails db:migrate

💡 By default, every new lead won't have an unsubscribed_at date. That field can be populated later when you need to unsubscribe a lead from your comms.

Now let's take a moment to add a minimal validation on the email field and a simple class method that checks any time we want if a user is still subscribed :

# lead.rb
class Lead < ApplicationRecord
  validates :email, presence: true, uniqueness: true

  def unsubscribed?

2. Create a controller for the lead form

rails generate controller Leads create  --no-helper --no-assets --no-controller-specs --no-view-specs

It should look like this :

class LeadsController < ApplicationController
  def create
    @lead = Lead.new(lead_params)
    if @lead.save
      redirect_to root_path, notice: "💌 Thanks for subscribing! We'll keep you informed."
      redirect_to root_path, notice: "Oops something went wrong!"


  def lead_params

3. Set up routes

Add a route for your leads form:

# config/routes.rb
resources :leads, only: [:new, :create]

4. Insert your form in your desired page

# app/views/pages/home.html.erb
<%= form_for(@lead) do |form| %>
  <%= form.label :email %>
  <%= form.email_field :email %>
  <%= form.submit 'Submit' %>
<% end %>

Because I'm inserting it in my homepage, I need to make @lead accessible to the PagesController, like so :

class PagesController < ApplicationController
  def index
    @lead = Lead.new

And voilà! You now have a functional form that can bring leads straight to your database and you can access the active ones with Lead.where(unsubscribed_at: nil)