rails link_to and button_to with bootstrap button class behaves differently

Atarang picture Atarang · Dec 24, 2014 · Viewed 7.6k times · Source

I've following link_to on show article view page,

<%= link_to "Add Pictures",
      new_picture_path(article_id: @article.id),
      class: "btn btn-small btn-success" %>

This works perfectly by displaying 'link' as a button with the help of "btn" class. Only problem with this is that the text on the button changes to gray after a click (as in visited link visited). How do I keep it as original text color (white in this case)? Or what kinds of css magic do I need to keep the original text color.

Or simply I can fix it by changing it to button_to as follows,

<%= button_to "Add Pictures",
      new_picture_path(article_id: @article.id),
      method: :get, class: "btn btn-small btn-success" %>

But the problem with this is that, my article_id is get sets to nil, which fails the validation error that article_id is not set.
What do I do? Fix the link_to with css (how?) or fix the button_to issue (how?). Any help is appreciated.

Answer

zhaoqing picture zhaoqing · Sep 14, 2016

If your css code contains:

a:visited {
  color: #666666;
}

This may cause a different rendering between link_to and button_to because link_to will be parsed as <a href=""></a> and button_to will be parsed as <form>..</form>.

Note: if you use

<%= button_to 'Users', users_path(app_id: application.id), method: :get, class: 'btn btn-info btn-xs' %>

Rails will compile as:

<form class="button_to" method="get" action="/users?app_id=1">
   <input class="btn btn-info btn-xs" type="submit" value="Users">
</form>

But the app_id=1 will not be passed to params in rails after you click on the button.

The solutions are :

  1. Use link_to with class attribute: style: "color:white" just like @Rahul says.

  2. Remove the css code: a:visited