Instance variable in partial view

91 Views Asked by At

I have a navbar that is a partial view that I need to render on a devise page for the user to edit their profile. As it is, I only have one page, but adding the path to perform account maintenance has messed up my navbar loading because of the instance variable not being present. How can I get a global instance variable that works across the board for my navbar, no matter what?

application_helper.rb

def get_company
  @company = current_user.company
end

def get_locations(company)
  @locations = if @company
    current_user.company_locations.order(:name)
  else
    []
  end
end

pages_controller.rb

def home
  @company = get_company
  @locations = get_locations(@company)
  @reports = if @company
    @company.reports.order("created_at DESC").limit(5)
  else
    []
  end
end

views/devise/registrations/edit.html.erb

<%= render partial: "pages/navigation" %>
... devise form ....

pages/_navigation.html.erb

<li class="right-menu-item">
      <button class="btn dropdown-toggle " type="button" id="dropdownMenu1" data-toggle="dropdown">
        <% if @company %>
          <%= @company.name %>
        <% else %>
          <%= current_user.email %>
        <% end %>
        <span class="caret"></span>
      </button>
      <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1">
        <% @locations.each do |location| %>
          <li role="presentation">
            <%= link_to root_path(location_id: location.id), role: "menuitem", tabindex: "-1" do %>
              <%= image_tag "check-green.svg" if location == @location %>
              <span><%= location.name %></span>
            <% end %>
          </li>
        <% end %>
      </ul>

Where the issue lies: enter image description here

What am I missing here to get this working across all views?

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

Ok, seems that Where is the controller of Devise ? how to add data from other models in users/edit page? was helpful. I had to do the following to make this work in the partial for the devise views:

rails g devise:controllers users -c registrations

which made a registrations controller under controllers/users/registrations.rb, then i was able to add the instance variables I needed do the edit method:

def edit
  @company = get_company
  @locations = get_locations(@company)
end

Had to also change the route.rb file around a little to facilitate the new controller:

devise_for :users, skip: [:sessions],
                   controllers: {
                     registrations: 'users/registrations'
                   }