Haml: link_to vs button_to
Asked Answered
S

5

12

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?

Seriema answered 29/4, 2012 at 17:35 Comment(0)
H
19

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.

Halfdan answered 29/4, 2012 at 17:49 Comment(1)
this adds method: 'post' not data-method: 'post' to the linkPrinz
C
4

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.

Cailean answered 29/11, 2015 at 6:39 Comment(0)
V
3

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.

Varden answered 29/4, 2012 at 18:37 Comment(0)
S
2

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

Sent answered 29/4, 2012 at 17:50 Comment(0)
S
1

Updated for rails 7

Making a post request from a link:

link_to method:

<%= link_to "Add to cart", line_items_path(product.id), data: {turbo_method: :post} %>

button_to method:

<%= button_to "Add to cart", line_items_path(product.id) %>
Septuplicate answered 12/3, 2023 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.