Derek Kelmanson Jr. Derek Kelmanson Jr. - 7 months ago 45
Ruby Question

Rails loop, link_to model_view

Rails: Need help looping through model array to link to the show page. I want to show the name, but link to the path. Seems like it should be simple but I have been coding all night and my brain is fried! please help.

<div class="container">
<div class="row">
<% @bars.each do |bar| %>
<div class="col-xs-6 something">
<div class="firstBar">
<%= link_to bars_path %>
<% end %>
</div>
</div>
</div>
</div>

Answer

This should work:

<div class="container">
  <div class="row">
    <% @bars.each do |bar| %>
      <div class="col-xs-6 something">
        <div class="firstBar">
          <%= link_to bar.name, bar %>
        </div>
      </div>
    <% end %>
  </div>
</div>

You could also do <%= link_to bar.name, bars_path(bar) %>, but is prettier to just give the object. Rails will know which Url helper to use given a specific object.

Take a look at the UrlHelper documentation