1
\$\begingroup\$

I want to display a town name in my navigation, depending on the town I am requesting from the model. The following code works, but I am mixing logic in my view which I know is wrong and I haven't been successful in accessing the @town instance variable from my TownsController.

Can someone lead me down the road to enlightenment in a situation like this? Should I be using a helper? How do I access it in my _header.html.erb partial?

<li class="name">
   <% @towns = Town.all %>
   <% @towns.each do |t| %>
      <h1><%= link_to "#{t.name}", '#', id: "logo" %></h1>
   <% end %>
</li>
\$\endgroup\$
2
\$\begingroup\$

Is _header.html.erb part of the layout? If so, i would advice you to move this logic to helper, if not all the controllers would need to set the @towns instance variable.

module ApplicationHelper
  def town_names
    Town.all.collect(&:name)
  end
end

And in your view call the town_names. I think you want each name to be in an li element. I have changed the code accordingly.

<% town_names.each do |name| %>
     <li class="name">
       <h1><%= link_to name, '#', id: "logo" %></h1>
     </li>
   <% end %>
\$\endgroup\$
  • \$\begingroup\$ You should not be doing ActiveRecord queries in a view helper. Instead, do set the @towns instance variable in all required controller actions using a before_filter. \$\endgroup\$ – Justin Force Feb 23 '15 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.