Ruby-on-rails – Using Rails link_to for links that post


I have a link that I need to submit a post request with. Normally, I'd use jQuery and prevent the link's default behavior and then submit a form to the destination. This seems like something Rails should be able to help me out with. Sure enough, the link_to method has an option for specifying a POST http method:

link_to "Profile", '', method: :post

That works, but I need to add 2 parameters too. I tried:

link_to "Profile", '', method: post, param1: 'value1', param2: 'value2'

That just added those parameters to the <a> HTML element, but didn't submit those when clicking the link:

<a rel="nofollow" param1="value1" param2="value2" data-method="post" href="">Profile</a>

Is there a way to do a POST request with parameters using link_to or any other Rails method? I'm using Rails 3.2.9.

Best Solution

The short answer is that if what you mean by "parameters" is form fields, then you simply can't do this (at least not in a straightforward way that I can see). You should instead use a form with a submit button, styled to look like a link (if that's what you want it to look like).

If on the other hand you had meant query parameters, then this would work:

link_to "Profile", profile_path(, param1: 'value1', param2: 'value2'), method: :post