28

I'm new to Rails, and I'm trying to use the link_to helper to create a link that issues a PUT request instead of a GET request. Specifically, I'm trying to create a link that activates a user's account in my app from the admin's panel. I'm using Rails 3.0.5.

My routes.rb file has:

match '/admin/users/:id/activate' => 'admin#activate_user',
  :action => :activate_user, :via => :put

My view has:

link_to 'Activate', :action => :activate_user, :id => user.id, :method => :put

However this generates the URL (for example) /admin/users/7/activate?method=put with the source code <a href="/admin/users/7/activate?method=put">Activate</a>.

I'd like to generate, instead, <a href = "/admin/users/7/activate" data-method="put">Activate</a>

I realize I could use button_to, but I've been wrestling with this issue for a while and I'm confused why I'm seeing this behavior, when other tutorials say that what I'm doing should be valid. How can I go about creating a link_to helper with the behavior I want?

maksim
  • 806
  • 2
  • 9
  • 16

3 Answers3

40

Updated - The link_to helper will do a GET unless a method is specified.

Its better specifying the exact request type, instead of match in your routes file. How about replacing match by put in routes as :

put '/admin/users/:id/activate' => 'admins#activate_user', :as => 'activate_user'

link_to 'Activate', activate_user_path(user.id), method: :put

The activate_user method should reside in admins controller. The docs has more info on link_to helper.

prasvin
  • 3,009
  • 23
  • 28
32

link_to thinks that :method => :put is part of the path hash. You have to tell it otherwise. Wrap your path in brackets.

link_to 'Activate', {:action => :activate_user, :id => user.id}, :method => :put

Now link_to will recognize :method => :put as an option, not part of the link's path.

As a side note, you should try to use route helpers instead of path hashes whenever possible. Keeps things nice and tidy, and avoids nit-picky situations like this.

Substantial
  • 6,684
  • 2
  • 31
  • 40
0

If You are using link_to do then you can use the following syntax

<%= link_to admin_subscription_path(user), method: :put do %>
 # can put html & css here
<% end %>
Striped
  • 2,544
  • 3
  • 25
  • 31