Contact us functionality in Rails 3

前端 未结 4 1558
不知归路
不知归路 2020-12-12 18:29

I want to make a contact us form in Rails 3 with the following fields:

  • Name
  • Email
  • Message title
  • Message body

The post

4条回答
  •  感情败类
    2020-12-12 18:49

    I updated the implementation to be as close as possible to the REST specification.

    Basic setup

    You can use the mail_form gem. After installing simply create a model named Message similar as it is described in the documentation.

    # 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
    

    This will already allow you to test sending emails via the console.

    Contact page

    In order to create a separate contact page do the following.

    # 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
    

    Setup the routing ..

    # config/routes.rb
    MyApp::Application.routes.draw do
      # Other resources
      resources :messages, only: [:index, :create]
      match "contact" => "messages#index"
    end
    

    Prepare a form partial ..

    // 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'
    

    And render the form in a view ..

    // app/views/messages/index.html.haml
    #contactform.row
      = render 'form'
    

提交回复
热议问题