2010-09-11 44 views
31

我希望做一個與我們聯繫Rails中形成3以下字段:聯繫我們的功能在Rails 3中

  • 名稱
  • 電子郵件
  • 信息標題
  • 消息體

發佈的消息打算髮送到我的電子郵件地址,所以我不一定必須將消息存儲在數據庫中。我必須使用ActionMailer,任何寶石或插件嗎?

+1

你可能有興趣閱讀寧靜,聯繫方式,以及:HTTP://機器人。 thinkbot.com/post/159807170/restful-contact-forms – sivabudh 2011-09-29 03:04:43

+0

噢,謝謝,這很有幫助:) – rodrigoalves 2011-10-05 19:01:25

回答

66

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

更新:

This article是一個比我更早發佈一個更好的例子,完美的作品

第二次更新:

我還建議合併-123中列出的一些技術在active_attr寶石,其中瑞安貝茨引導你完成爲聯繫頁面設置tabless模型的過程。

第三次更新:

我寫我自己test-driven blog post

+1

這是過時的,並使用不必要的支持模式。雖然仍然+1,因爲它提高了我的理解:) – 2012-01-19 22:00:30

+0

同意的Abe,我添加了一些新的鏈接等 – stephenmurdoch 2012-06-03 21:02:32

+0

你碰巧知道如何在連接的文章的模型中列出attr_accessors?我在.yml中定義了以下內容,但在相應的錯誤消息中忽略了它。 'de.activerecord.attributes.message.subject:Betreff' – user569825 2012-06-11 08:55:54

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 => "[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' 
+0

我試試這個,但是,你把你的SMTP配置。這個聯繫表格可以在localhost環境中工作嗎? – Stanmx 2013-07-24 06:25:04

+0

@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

+0

謝謝@JJD,我從另一個例子開始,但是我每次發送,我都收到了:錯誤的參數(Fixnum)! (期望種類的OpenSSL :: SSL :: SSLContext) – Stanmx 2013-07-24 08:55:24

-1

您可以通過這個鏈接使用聯繫我們的寶石:https://github.com/JDutil/contact_us 的文件是明確的,你可以簡單地使用它。

特點:

  1. 驗證
  2. 易/添加刪除字段
  3. 簡單的配置