Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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", 'http://example.com/profile', method: :post 

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

link_to "Profile", 'http://example.com/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="http://example.com/profile">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.

like image 688
at. Avatar asked Nov 16 '12 10:11

at.


People also ask

How does Link_to work in Rails?

Rails is able to map any object that you pass into link_to by its model. It actually has nothing to do with the view that you use it in. It knows that an instance of the Profile class should map to the /profiles/:id path when generating a URL.

How do I link pages in Ruby on Rails?

open index. html. erb file in app>>views>>home folder use in atom editor. After you open index file now add following HTML link code in that file and end with <br /> tag.

How do I create a link in rails?

The rails link_to is a helper which helps us in creating a hyperlink to the existing main document. The Rain link_to will be created as anchor tag or the h-ref tag. Anchor tag is known as an HTML code that creates another link to another page or to a specific section of the existing document.


1 Answers

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(@profile.id, param1: 'value1', param2: 'value2'), method: :post 
like image 126
Chris Salzberg Avatar answered Sep 19 '22 11:09

Chris Salzberg