Я обновил реализацию, чтобы она была максимально приближена к спецификации REST.
Базовая настройка
Вы можете использовать mail_form gem .После установки просто создайте модель с именем Message
, аналогичную описанной в документации.
# app/models/message.rb
class Message < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
attribute :message_title, :validate => true
attribute :message_body, :validate => true
def headers
{
:subject => "A message",
:to => "contact@domain.com",
:from => %("#{name}" <#{email}>)
}
end
end
Это уже позволит вам проверить отправку писем через консоль .
Страница контактов
Чтобы создать отдельную страницу контактов, выполните следующие действия.
# app/controllers/messages_controller.rb
class MessagesController < ApplicationController
respond_to :html
def index
end
def create
message = Message.new(params[:contact_form])
if message.deliver
redirect_to root_path, :notice => 'Email has been sent.'
else
redirect_to root_path, :notice => 'Email could not be sent.'
end
end
end
Настройка маршрутизации ..
# config/routes.rb
MyApp::Application.routes.draw do
# Other resources
resources :messages, only: [:index, :create]
match "contact" => "messages#index"
end
Подготовка частичной формы..
// app/views/pages/_form.html.haml
= simple_form_for :contact_form, url: messages_path, method: :post do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.input :email, label: 'Email address'
= f.input :message_title, label: 'Title'
= f.input :message_body, label: 'Your message', as: :text
.form-actions
= f.submit 'Submit'
И отрисовать форму в виде ..
// app/views/messages/index.html.haml
#contactform.row
= render 'form'