0

I am stumped. I want to use an instance variable in my navbar to show dynamic content from a table.

In terms of file structure, within my Views, I have a /layouts folder. Within that folder, there is a _header.html.erb for the navbar that is placed in the view through <%= render 'layouts/header' %> in application.html.erb file.

Now here's where it gets sticky. In my navbar, I have a set of links. I want it to render an instance variable as a link (the text it shows, not the path), so I am writing:

 <ul class="nav navbar-nav navbar-right">
      <li><%= link_to "About", about_path %></li> 
          <li><%= link_to "Settings", edit_user_registration_path %></li>
           <li><%= link_to "My Example", myexample_path %></li> 
           <li><%= link_to @example, stack_path %></li>
  </ul>

I have tried doing two different things with the instance variable.

So I need to define @example = Stack.where(user_id: current_user.id).pluck(:points) to return a number that I want to place in that navbar. I have tried putting that instance in the Application Controller and by making a Layouts Controller and placing it there in def index.

Therefore, my question is: to create an instance variable to be read by this _layouts.html.erb file, which controller is appropriate to use?

As a final note, whether I add it to the Application Controller or Layouts Controller, it simply doesn't render. If I remove the @example instance and instead put static text, it will add it to the navbar. So this seems to be my issue.

5
  • <%= render 'header' %> try this or put header.htm.erb in shared directory and use this <%= render 'shared/header' %> Commented Apr 12, 2016 at 4:17
  • @uzaif - Just to be clear, the layouts/_header.html.erb is actually rendering, all except the dynamic content. I am confused as to which controller needs to be used to connect it to the header file if I want to store an instance variable. Does your solution address that? Commented Apr 12, 2016 at 4:24
  • write method in application controller and access it with before filter return the variable which you need in header.html.erb Commented Apr 12, 2016 at 4:27
  • That works. Thank you! Commented Apr 12, 2016 at 4:32
  • can i post as answer ? Commented Apr 12, 2016 at 4:33

1 Answer 1

2

in application controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_filter :add_header_text

  def add_header_text
   @menu = Menu.all 
  end

end

Now @menu instance variable is available in header partial

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.