联系我们Rails 3中的功能

时间:2010-09-11 03:49:51

标签: ruby-on-rails forms email contact mail-form

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

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

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

4 个答案:

答案 0 :(得分:66)

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

<强>更新

This article是一个比我之前发布的更好的例子,工作完美无缺

第二次更新:

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

第三次更新:

我写了自己的test-driven blog post关于它

答案 1 :(得分: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

这将允许您测试sending emails via the console

联系页面

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

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

答案 2 :(得分:1)

我无法使这个示例的代码工作,我认为这会让你的事情变得有点复杂。

Anywat,我制作了一份工作联系表格并在博客上发表了这篇文章..文本是葡萄牙文,但代码本身(大部分)是英文版http://www.rodrigoalvesvieira.com/formulario-contato-rails/

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

答案 3 :(得分:-1)

您可以通过以下链接使用“联系我们”宝石:https://github.com/JDutil/contact_us 文档很清楚,您可以简单地使用它。

特点:

  1. 验证
  2. 简易/添加删除字段
  3. 简单配置