dev
dev

Reputation: 1507

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.

Upvotes: 5

Views: 27275

Answers (2)

Seb Wilgosz
Seb Wilgosz

Reputation: 1250

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" class="button_to">
  <div><input class="my_class" id="my_id" value="New" type="submit" /></div>
</form>"

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

Upvotes: 1

damoiser
damoiser

Reputation: 6238

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: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to

For example:

<%= button_to "New", action: "new" %>
# => "<form method="post" action="/controller/new" class="button_to">
#      <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.

Upvotes: 13

Related Questions