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
感謝您的。是否可以簡要描述添加這種功能的正確方法?我的意思是,我應該更改哪些文件 - 只是我的表單視圖的控制器,或者我必須創建一個新的控制器,例如..? – phi 2010-09-09 07:43:01
嗨艾琳。我已經添加了一個例子。 – mark 2010-09-09 08:27:25
我知道這種評論在這裏不受歡迎,但你的回答非常有用 - 非常感謝你。 – phi 2010-09-10 08:12:25