Skip to content

Instantly share code, notes, and snippets.

@joeljunstrom
Last active May 21, 2020 11:56
Show Gist options
  • Save joeljunstrom/294f8fa24932d006cde49ba5d4f8c67f to your computer and use it in GitHub Desktop.
Save joeljunstrom/294f8fa24932d006cde49ba5d4f8c67f to your computer and use it in GitHub Desktop.
# config/routes.rb
Rails.application.routes.draw do
resource :contact_message, only: [:new, :create], path: "/contact", path_names: {new: "/"}
end
# app/controllers/contact_messages_controller.rb
class ContactMessagesController < ApplicationController
def new
render locals: {form: ContactMessageForm.new}
end
def create
form = ContactMessageForm.new(contact_message_params)
if form.valid?
VisitorMailer
.with(recipient: form, message: form.message)
.contact_email
.deliver_later
redirect_to root_path
else
render "new", locals: {form: form}
end
end
private
def contact_message_params
params
.require(:form)
.permit(:name, :email, :phone, :message)
end
end
# app/forms/contact_message_form.rb
class ContactMessageForm
include ActiveModel::Model
attr_accessor :name, :email, :phone, :message
validates_presence_of :name, :email, :message
validates :email, email_address: true, allow_nil: true
end
# app/views/contact_messages/new.html.erb
<%= form_for(form, as: :form, url: contact_messages_path) do |f| %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment