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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With