Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haml: link_to vs button_to

From what I understand, link_to is used for get methods, and button_to is used for post methods.

On the other hand, I was told that with HTML5 semantics, <button> is used for any type of clickable...well, button. In the case I have a clickable button that sends a user to a form to fill out, should I create a button_to or a link_to?

like image 597
Karan Avatar asked Apr 29 '12 17:04

Karan


4 Answers

It's simpler that you think. That methods are Rails helpers and don't have anything to do with haml. Yes, one method is for get and another for post methods. If you need to post any data to controller, use button_to (for example when deleting a record). Otherwise, link_to is enough.

Moreover, you can make link_to posting data using :method parameter:

= link_to "Something", some_path, :method => :post

Answering your question, use link_to.

like image 69
methyl Avatar answered Sep 17 '22 06:09

methyl


The main principle difference between the #link_to, and #button_to is that the #link_to just creates a link tag A, and makes simple AJAX request without an additional data, while #button_to creates a FORM with a custom data, so the form can be used to make extended AJAX request to a webserver. The form data includes embedded CSRF-token, which is used to authentication the request. In case of #link_to CSRF-token must be serualized and send in on_click event.

like image 45
Малъ Скрылевъ Avatar answered Sep 18 '22 06:09

Малъ Скрылевъ


You should use links to point the user to a resource, like an article.

But you have to tend to use buttons to point to an action(like "Create"/"Send" on your edit page). If this doesn't agree with your interface -- style them like as a link.

Here's why: you cannot point your user to any non-GET action via link_to if he lacks the javascript support. So, buttons are the only options to make your send/destroy action to be triggered in this case.

Feel free to use both approaches if your link points to a page that eventually leads to a modification of a resource (link/button to an edit/create page that shows a form), like in your case.

like image 37
jdoe Avatar answered Sep 19 '22 06:09

jdoe


If you want to simply send a user to somewhere, it is get request. So you should use link_to in this case. By the way, you can use the link_to for post requests and other requests (like button_to too) if you will specify :method. For example: =link_to "some path", some_path, :method => :get

like image 26
Mik Avatar answered Sep 20 '22 06:09

Mik