Tag Archives: ruby

Using link_to in rails with :confirm and :method

Every time i’m going to use the link_to method in rails, I always seem to get a lot of errors.

The documentation states:

link_to(name, options = {}, html_options = nil)
link_to(options = {}, html_options = nil) do
# name

URL to the rails docs: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001597

And gives a list of options you can set. However, I always seem to have problems remembering the correct syntax if I want to use :confirm and :method.

After fiddling with it a bit, I found that the proper way of using is:

%lt%= link_to(
    :action => "destroy",
    :id => some_id
  :method => :delete,
  :confirm => t('Are you sure you want to delete it?')
) %>

My biggest problem was, that you do not need to add the controller.

Also, found a nice write up about this on Ryan’s Scraps blog (a bit old post, but still…)

Hope you can use the tip.

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 %>