Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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>
share|improve this question

1 Answer 1

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 %>
share|improve this answer
    
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. –  Justin Force Feb 23 at 18:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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