Use Rails’ form_tag with care

Today at work I was fiddling with some forms in an admin interface. When I had to make an update form, the data didn’t hit the correct controller action.

If you ever get the message ActionController::MethodNotAllowed, then you’ve created your form wrong!

The error came when I tried doing:

<% form_tag :action => :update, :method => :put do %>
  lots of fields here
<% end %>

The data was not sent correctly (it was sent as POST, not as PUT as I wanted) and the action was not found. After googling for a bit, I found out that others had a similar problem.

The answer was rather simple though. In the rails docs you use the form_tag like this:

form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)

What I didn’t realize straight away was, that my :method => put was being sent in the first hash and NOT the second as it was suppose to.
So if you are creating your own forms, without activerecord, do it like this:

<% form_tag({:action => :update}, {:method => :put}) do %>
  lots of fields here
<% end %>