联系我们Rails 3中的功能

rod*_*ves 31 forms email ruby-on-rails contact mail-form

我想在Rails 3中与以下字段联系我们:

  • 名称
  • 电子邮件
  • 消息标题
  • 邮件正文

发布的消息旨在转到我的电子邮件地址,因此我不一定必须将消息存储在数据库中.我必须使用ActionMailer任何宝石或插件吗?

ste*_*och 66

教程是一个很好的例子 - 它是Rails 3

更新:

这篇文章比我之前发布的文章更好,工作完美无缺

第二次更新:

我还建议在active_attr gem中合并这个railscast中概述的一些技术,其中Ryan Bates将指导您完成为联系页面设置tabless模型的过程.

第三次更新:

我写了一篇关于它的测试驱动的博客文章


JJD*_*JJD 9

我将实现更新为尽可能接近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
Run Code Online (Sandbox Code Playgroud)

这将允许您通过控制台测试发送电子邮件.

联系页面

要创建单独的联系页面,请执行以下操作.

# 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
Run Code Online (Sandbox Code Playgroud)

设置路由..

# config/routes.rb
MyApp::Application.routes.draw do
  # Other resources
  resources :messages, only: [:index, :create]
  match "contact" => "messages#index"
end
Run Code Online (Sandbox Code Playgroud)

准备一份表格..

// 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'
Run Code Online (Sandbox Code Playgroud)

并在视图中呈现表单..

// app/views/messages/index.html.haml
#contactform.row
  = render 'form'
Run Code Online (Sandbox Code Playgroud)