2010-09-08 100 views
0

我在.erb文件中有一個表單,用戶可以在其中輸入一些信息。然後,我想對另一個URL進行POST(比如說www.3rdparty.com/api.php?f=add_entry),它將以0或1回覆,以獲得成功或失敗。哪一條是正確的路要走,特別是如果我想留在頁面上,然後根據迴應顯示對話框?我沒有Ruby on Rails的經驗,所以我甚至不確定這是否可行,或者是否應該向控制器添加功能。因此,我會很感激,如果你能提供初學者細節:)如何向第三方發佈POST並使用Ruby on Rails獲得結果?

感謝, 艾琳

回答

5
require 'net/http' 
url = URI.parse('http://www.3rdparty.com/api.php?f=add_entry') 
args = {'arg1' => 'data' } 
response = Net::HTTP.post_form(url, args) 

參見:

http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

# routes.rb 
map.resources :books, :member => {:status => :get}#status route member optional - see below 

# book_controller.rb 
def new 
    @book = Book.new 

# new.html.erb 
form_for @book, :url => books_path do |f| 
    <%= f.fields_for :title -%> 
    <%= f.fields_for :isbn -%> 

#book_controller.rb 
def create 
    @book = Book.new params[:book] 
    if @book.save 
    redirect_to status_book_path @book #optional 
    # no need to redirect. Create a create.html.erb and it will be rendered by default 

#book.rb #model 
before_create :verify_isbn 

private 
def verify_isbn 
    require 'net/http' 
    url = URI.parse('http://www.3rdparty.com/api.php?f=add_entry') 
    args = {:isbn => isbn }#here the latter isbn is a field of your model 
    response = Net::HTTP.post_form(url, args) 
    errors.add(:isbn, "That isbn is not valid") unless response.to_i == 1 
end 
+0

感謝您的。是否可以簡要描述添加這種功能的正確方法?我的意思是,我應該更改哪些文件 - 只是我的表單視圖的控制器,或者我必須創建一個新的控制器,例如..? – phi 2010-09-09 07:43:01

+0

嗨艾琳。我已經添加了一個例子。 – mark 2010-09-09 08:27:25

+0

我知道這種評論在這裏不受歡迎,但你的回答非常有用 - 非常感謝你。 – phi 2010-09-10 08:12:25