31

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

  • 姓名
  • 电子邮件
  • 留言标题
  • 邮件正文

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

4

4 回答 4

66

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

更新:

这篇文章是一个比我之前发布的更好的例子,完美无缺

第二次更新:

我还建议在active_attr gem上合并此 railscast中概述的一些技术,Ryan Bates 将引导您完成为联系页面设置表格模型的过程。

第三次更新:

我写了我自己的测试驱动博客文章

于 2010-09-11T14:20:24.553 回答
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

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

联系页面

为了创建一个单独的联系页面,请执行以下操作。

# 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'
于 2013-04-26T13:19:51.930 回答
1

我无法使此示例的代码正常工作,而且我认为自从您创建模型以来它使事情变得有些复杂。

Anywat,我制作了一个工作联系表并在博客上写了它。文本是葡萄牙语,但代码本身(大部分)是英文http://www.rodrigoalvesvieira.com/formulario-contato-rails/

注意:我使用的是 sendmail,而不是 SMTP。

于 2011-07-25T19:43:18.120 回答
-1

您可以通过此链接使用 Contact Us gem:https ://github.com/JDutil/contact_us 文档清晰,您可以简单地使用它。

特征:

  1. 验证
  2. 简单/添加删除字段
  3. 简单配置
于 2016-03-09T19:04:56.553 回答