联系我们的功能在Rails 3中
我希望做一个与我们联系Rails中形成3以下字段:联系我们的功能在Rails 3中
- 名称
- 电子邮件
- 信息标题
- 消息体
发布的消息打算发送到我的电子邮件地址,所以我不一定必须将消息存储在数据库中。我必须使用ActionMailer
,任何宝石或插件吗?
This教程是一个很好的例子 - 它的Rails 3
更新:
This article是一个比我更早发布一个更好的例子,完美的作品
第二次更新:
我还建议合并-123中列出的一些技术在active_attr宝石,其中瑞安贝茨引导你完成为联系页面设置tabless模型的过程。
第三次更新:
我写我自己test-driven blog post它
这是过时的,并使用不必要的支持模式。虽然仍然+1,因为它提高了我的理解:) – 2012-01-19 22:00:30
同意的Abe,我添加了一些新的链接等 – stephenmurdoch 2012-06-03 21:02:32
你碰巧知道如何在连接的文章的模型中列出attr_accessors?我在.yml中定义了以下内容,但在相应的错误消息中忽略了它。 'de.activerecord.attributes.message.subject:Betreff' – user569825 2012-06-11 08:55:54
我不能让这个例子中工作的代码,我认为它使事情有点复杂,因为你创建模型。
Anywat,我做了工作联系表,并在博客吧..文字是葡萄牙语,但代码本身(大部分)在英语http://www.rodrigoalvesvieira.com/formulario-contato-rails/
注:我用的sendmail,没有SMTP。
我更新了实现以尽可能接近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 => "[email protected]",
: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'
我试试这个,但是,你把你的SMTP配置。这个联系表格可以在localhost环境中工作吗? – Stanmx 2013-07-24 06:25:04
@Stanmx SMTP配置进入'config/environment/development.rb'或'../ production.rb'。 [文档描述了GMail的设置](http://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration-for-gmail),它也可以在localhost上运行。 – JJD 2013-07-24 08:47:14
谢谢@JJD,我从另一个例子开始,但是我每次发送,我都收到了:错误的参数(Fixnum)! (期望种类的OpenSSL :: SSL :: SSLContext) – Stanmx 2013-07-24 08:55:24
你可能有兴趣阅读宁静,联系方式,以及:HTTP://机器人。 thinkbot.com/post/159807170/restful-contact-forms – sivabudh 2011-09-29 03:04:43
噢,谢谢,这很有帮助:) – rodrigoalves 2011-10-05 19:01:25