marcamillion
marcamillion

Reputation: 33795

Which controller does a partial in my `views/layouts` work with?

I tried adding @categories = Category.all in my ApplicationController.

But when I click on one of my views, it doesn't work - it seems @categories is nil when it shouldn't be.

I would like to generate a menu in my _navigation.html.erb partial in my layouts folder.

Where do I declare the @categories instance variable to be used in a partial that will be used on all of my views if not in my Application Controller?

Thanks.

Upvotes: 1

Views: 47

Answers (2)

Rahul
Rahul

Reputation: 412

If it's going to be used in all your views, maybe you can define a helper.

def all_categories
 @categories ||= Category.all
end

You can access it in all your views using all_categories.

UPDATE:

If you wish to define all_categories in your controller, use helper_method

helper_method :all_categories

Upvotes: 2

dan1d
dan1d

Reputation: 151

use before_filter in application controller, it execute any method before the action you call

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :some_action

  def some_action
   @categories = Category.all
  end 
end

You should read this

Upvotes: 1

Related Questions