开发者

How to make a POST to a third party and get the result back with Ruby on Rails?

I'm having a form in a .erb file, where the user can enter some info. Then I want to make a POST to a different URL (let's say www.3rdparty.com/api.php?f=add_entry), that will reply with 0 or 1, for success or failure. Which is the right way to go, especially if I want to stay on the page with the form, and then show a dialog according to the response? I have no experience in Ruby on Rails, so I'm not even sure if this is possible, or if I should add functionality to the controller. Thus, I would really appreciate it if you could provide be开发者_JS百科ginner details :)

Thanks, Irene


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)

See:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜