Rashed Al-Julaibi
Rashed Al-Julaibi

Reputation: 281

How to make links for index and show actions work in partial views

I am using a partial to render a nav bar from the layouts folder in all my pages, and within the nav bar I have links to actions such as index and show from a GradesController. I understand that in order for the links to work I must call them in that page's action in the controller as such:

def home
  @grades = Grade.all 
end

However as these links exist within a partial view which doesn't have a corresponding controller, how can I make these links work without getting a NoMethodError?

layouts/_navbar.html.erb

<div class="main_nav_color">
  <div class="wrapper">
    <header id="main_header" class="cf">
      <a href="#" id="logo">arabecademy</a>
        <nav>
          <ul>
            <li>
              <%= link_to "#" do %>
                Grade<span class="glyphicon glyphicon-chevron-down"></span>
              <% end %>
              <ul>
               <% @grades.each do |grade| %>
                  <li><%= link_to "Grade" + grade.grade_number, grade_courses_path(grade, @course) %></li>
                <% end %>
              </ul>
            </li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
            <% if student_signed_in? %>
            <li><%= link_to "Log Out", destroy_student_session_path, method: :delete %></li>
            <li><%= link_to "Accout Settings", edit_student_registration_path %></li>
            <% else %>
            <li><%= link_to "Log in", new_student_session_path %></li>
            <li><%= link_to "Sign Up", new_student_registration_path, :class => "button_sm button_orange" %></li>
            <% end %>
          </ul>
        </nav>
    </header>
  </div>
</div>

Upvotes: 0

Views: 36

Answers (1)

Matt Gibson
Matt Gibson

Reputation: 14959

To get @grades set all the time, you can add a before_filter in ApplicationController like this:

class ApplicationController
  before_action :load_grades

  def load_grades
    @grades = Grade.all
  end
end

This will make sure that every single controller action has @grades set in addition to whatever the action itself does. Your partial should be able to pick up @grades wherever you display it now.

Upvotes: 1

Related Questions