adding a class to a link_to is breaking the link adding a class to a link_to is breaking the link ruby-on-rails ruby-on-rails

adding a class to a link_to is breaking the link


<%= link_to "Add to your favorites list",{:controller =>             'favourite_companies', :action =>'create'},             :company_id=>"#{@company.id}",               :company_name=>"#{@company.company_name}",            :class=>"ui-button-text button_text"}  %>

try this

<%= link_to "Add to your favorites list", :controller =>             'favourite_companies', :action =>'create',             :company_id=>"#{@company.id}",               :company_name=>"#{@company.company_name}",            { :class=>"ui-button-text button_text" }  %>

Since the :class should be in :html_options (refering to API)

link_to(body, url, html_options = {})


The proper way of doing what you have is as follows:

link_to "Foo", { URL_FOR PARAMS HERE }, :class => "bar"

As far as setting the controller and action manually like this, well, it's crap. Rails builds url helpers for you; use them and save yourself some time, energy, and add clarity, all at once:

link_to "Foo", favourite_companies_path(@company), :method => :post

What you're doing with the string interpolation is a bad idea too…it's just wasteful and cluttered for no reason at all. The following is the same, just better:

link_to "Foo", :company_id => @company.id, :company_name => @company.name

As far as why your link wasn't working, if wrapping it in a div helped it sounds like you have a problem with your HTML structure, not the link_to syntax.


I'm using a link_to do-end block so the above previous solutions didn't work for me.

If you want to embed other tags in your a tag, then you can use the link_to do-end block.

<%= link_to favourite_companies_path(:company_id => @company.id, :another_url_param_here => "bar"), { :class => "ui-button-text button_text", :title=> "We can have more html attributes as well" } do %>  <i class="fa fa-star"></i>  <%= @company.company_name %><% end %>

In this case it's

<%= link_to path(url_params), html_options = {} do %><% end %>