views:

47

answers:

1

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 beginner details :)

Thanks, Irene

+5  A: 
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
mark
Thanks for that. Is it possible to briefly describe a proper way of adding such functionality? I mean, which files should I change - just the controller of my form view or do I have to make a new controller for example..?
Irene
Hi Irene. I've added an example.
mark
I know this kind of comments is discouraged here, but your answer was really helpful - thank you so much.
Irene
Hey you're very welcome Irene. There's no discouragement of comments such as yours, quite the opposite in my understanding. :)
mark