Olivier Tremblay
Olivier Tremblay

Reputation: 1431

Sinatra PUT method not working?

For some reason, my "PUT" method isn't caught by Sinatra using this html. Can someone help me spot the mistake? When I use a "post" action in my controller, it works just the way it is expected...

<form method="post" action="/proposals/<%[email protected]%>/addItem">
<input type="hidden" name="_method" value="put"/>
  <div>
  <label for="item_id">Item list</label>
<select title="Item ID" id="item_id" name='item_id'>
  <%@items.each do |item|%>
    <option value="<%=item.id%>"><%=item.name%></option>
  <%end%>
</select>                                   
<input type="submit" value="Add"/></div>
<label for="new_item_name">Create new item</label>
<input type="text" id="new_item_name" name="new_item_name" />
<input type="submit" value="Create"/>
</form>

Upvotes: 4

Views: 6182

Answers (3)

awilkening
awilkening

Reputation: 1062

Be sure to include Rack::MethodOverride in your config.ru:

use Rack::MethodOverride

Upvotes: 15

Steffen Roller
Steffen Roller

Reputation: 3494

I just run into this and none of the tips above helped. What I found:

The form definition has to come up first with the action= and second with method=

correct form:

<form action="/putsomething" method="POST">
    <input type="hidden" name="_method" value="PUT" />
 ...
</form>

wrong form:

<form method="POST" action="/putsomething">
    <input type="hidden" name="_method" value="PUT" />
 ...
</form>

The first worked for me, the second didn't. Maybe this helps.

Upvotes: 0

AboutRuby
AboutRuby

Reputation: 8116

That all looks correct. It looks like you either wrote the route string wrong, or it's being caught by another route before your put method. I was curious about this so I wrote up a quick Sinatra app that used a put method, and it does indeed work this way.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'

get '/' do
  <<-eos
<html>
  <body>
    <form action="/putsomething" method="post">
      <input type="hidden" name="_method" value="put" />
      <input type="submit">
    </form>
  </body>
</html>
eos
end

put '/putsomething' do
  "You put something!"
end

Upvotes: 10

Related Questions