Help with main application layout, how to pre-load elements for each page?
My application.html.erb (main layout) has some categories on the top of the header, and the sidebar has some more data that is loaded from the database.
I don't want to have to load or make calls to the models each time in each action, and then pass this to the view etc.
How do I load data for the main application.html.erb file in a global way and not have to do it each time in my controller action's.
开发者_开发技巧Also, what if there is logic, such that certain things will be loaded in the application.html.erb that depends on the current action being called?
Put this "shared logic" in application_controller.rb since all your controllers extend it.
Use before_filter to execute a method where you assign some data to @instance_field that will be accessible in views. An example that makes @current_user accessible in every view:
class ApplicationController < ActionController::Base
before_filter :current_user
def current_user
@current_user ||= session[:current_user_id] && User.find(session[:current_user_id])
end
end
精彩评论