Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to create a method that will be available in all controllers, and views

i am making a ecommerce application in which the categories are visible in side bar on all pages. i wrote a method in application controller

def categories
  @categories = Category.all
end

but how can i make this method available to all controllers and actions by default so that i dont have to specifically call this method in every action

def list
  categories
  @products = Product.order('title').page(params[:page]).per(4)
end
like image 436
imran Avatar asked Jan 09 '12 13:01

imran


1 Answers

You can define your method in application_controller.rb and since every other controller inherits from this one, that method will be available to all the controllers. Also, to make it a helper method for it to be available in the views, you can say helper_method :my_method in the application_controller.rb.

Now, for it to be automatically evaluated before any other action in a controller, you can use a before_filter. Add before_filter :my_method in the controller you want this method to be evaluated before any action or in the application_controller.rb

like image 155
Syed Aslam Avatar answered Sep 30 '22 14:09

Syed Aslam