Rails button_to vs. HTML Button Tag

I am new to Rails and I am trying to add a few buttons to my page. I see that you can use both the HTML tag or the rails "button_to." However, I have not been able to find out the difference in each.

From what I have seen in S.O., it seems that button_to makes it easier to call functions from the controller, etc. However, HTML button seems easier to customize? Is this true? Are there other differences.

Just looking to ensure I am doing the correct thing on my new project. Thanks in advance.

2

2 Answers

button_to like all others helpers for the views in Rails (e.g. link_to, form_for, image_tag...) simply converts your Rails command in HTML code. We could say that is a shortcut to write "pure HTML".

In your case, for button_to, you can see the reference (and what is printed) here:

For example:

<%= button_to "New", action: "new" %> # => "<form method="post" action="/controller/new"> # <div><input value="New" type="submit" /></div> # </form>" 

I suggest you to use these helpers, because is more "Rails" and this improve your speed of coding.

3

button_to tag is as easy to customize as html tag.

There is a convention to not style HTML tags inside this elements but in included *.css files. All customization of your HTML tags should be addition of classes and ids.

To do it in rails you should use

<%= button_to "New", { action: "new" }, class: "my_class", id: "my_id" %> 

It will generate the html code like this:

<form method="post" action="/controller/new"> <div><input value="New" type="submit" /></div> </form>" 

As you see, using Rails helpers you can write the same functionality with less, more readable code.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like