2

I have a model an a controller for a pages resource. I need to be able to access the names of the pages and the pages and link_to from within the Application.html.erb

I have tried rendering a navigation partial. But you can't access the controller from a partial. I need to be able to render a navbar that has access the @pages variable so I can loop through them.

What's the best way to do this?

1 Answer 1

3

Inside your ApplicationController, app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :get_pages

  protected

  def get_pages
    @pages ||= Page.all
  end

end

This way you're able to use the @pages instance variable from within any view.

By using memoization through the ||= operator you're only assigning the variable the first time you need it, so no need to worry about calling that method every time.

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

3 Comments

Nicely done, even added variable caching there to make sure it only assigns its if it hasn't already been set. So will this work in the nav partial? A partials still a view right?
Right, this will work in any partial. That's the solution I've been using in my projects.
Glad to help. Just picking my answer as the correct one will be enough reward. :)

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.