2016-06-20 26 views
0

我有一個網頁上有兩種形式。 有一個一般的聯繫表單和一個購物車,如響應部分從客戶銷售人員迴應與客戶的選擇。如何配置Pony/Sinatra發送兩種不同形式的數據?

我對Ruby一無所知,而且我很難同化這些應該如何處理指向Sinatra電子郵件模板的路由。 如下代碼...

**** **** Mailer.rb

require 'sinatra' 
    require 'pony' 

    Pony.options = { 
     via: :smtp, 
     via_options: { 
     openssl_verify_mode: OpenSSL::SSL::VERIFY_NONE, 
     address: 'mail.myserver.com', 
     port: '587', 
     user_name: '[email protected]', 
     password: '********', 
     authentication: :plain, 
     domain: "mail.myserver.com" # the HELO domain provided by the client to the server 

     } 
    } 

class Mailer < Sinatra::Base 
    post '/contact' do 
    options = { 
     from: "[email protected]", 
     to: '[email protected]', 
     subject: "Contact Form", 
     body: "#{params['name']} <#{params['email']}> \n" + params['message'] 
    } 

    Pony.mail(options) 

    redirect '/' 
    end 

post '/build-tool' do 
    options = { 
     from: "[email protected]", 
     to: '[email protected]', 
     subject: "Custom Build Form", 
     body: "#{params['name']} <#{params['email']}> \n" + params['message'] 
    } 

    Pony.mail(options) 

    redirect '/' 
    end 

end 

***** HTML表單一個*****

<form class="form-horizontal" method="POST" action="/contact"> 
contact information inputs 
</form> 

* **** HTML表單兩個*****

<form class="form-horizontal" method="POST" action="/build-tool"> 
build tool inputs 
</form> 

***** Config.rb *****

map '/contact' do 
    run Mailer 
end 

map '/build-tool' do 
    run Mailer 
end 
+0

您對此代碼有具體問題嗎?基本上,小馬是一個郵件類,用於在您的sinatra應用程序發送郵件後形式submition。 –

+0

如何配置Pony/Sinatra從兩種不同的表單發送數據? – Gilgamesh415

回答

0
  1. 西納特拉直接計算出的路線,所以如果你犯了一個POST請求「/接觸」,它會調用post '/contact'定義裏面的代碼,這樣你就不必做任何你正在做的在config.rb

  2. 當你redirect '/',這意味着服務器期望定義一個根路由,這是你的類定義中缺少的。

  3. HTML標籤進入view,它通過Sinatra呈現。

這些是需要改變的三件事情。首先,我們定義一個/路線這使得我們需要的HTML表單元素:

# mailer.rb 

require 'sinatra/base' # note the addition of /base here. 
require 'pony' 

# pony options code same as before 

class Mailer < Sinatra::Base 
    get '/' do 
    erb :index 
    end 

    # post routes same as before 
end 

HTML會從視圖模板呈現。默認情況下,Sinatra將在views/目錄內查看視圖。

# views/index.erb 

<form class="form-horizontal" method="POST" action="/contact"> 
    contact information inputs 
    submit button 
</form> 

<form class="form-horizontal" method="POST" action="/build-tool"> 
    build tool inputs 
    submit button 
</form> 

ERB是一種與Ruby語言捆綁在一起的模板語言,因此您不必安裝任何新的gem。還有更多languages listed in the documentation.config.ru看起來像:

# config.ru 
# Note the file change. This is called a Rackup file. config.rb is 
# a more general purpose file used by many libraries, so it's better 
# to keep this separate. 

require_relative 'mailer.rb' 

run Mailer 
0

這裏的問題是,每個表單對應一個特定的路線,表單數據發送到該動作。換句話說,「form one」將它在POST請求中包含的所有輸入字段發送到/contact,「form two」將其所有輸入字段發送到POST/build-tool

我的建議是將兩個表單合併到一個表單中,然後使用頁面的樣式來使其看起來像兩個。這樣,您可以將所有輸入字段一起提交給您的Sinatra應用程序,並且您可以發送最適用於輸入內容的任何郵件。

相關問題