Reputation: 163
How can I get values from database in application.html.erb? I need to get those values for whole project. Those values will stay forever to all pages. How can I pass values to application.html.erb?
Is there anything like beforeRender? Is there anything like appcontroller.rb to override actions?
Upvotes: 1
Views: 770
Reputation: 3694
You could use an application wide before_filter
- like so
class ApplicationController < ActionController::Base
before_filter :load_application_wide_varibales
private
def load_application_wide_varibales
@var = Model.where :condition => "whatever"
end
end
@var
would then be available in all your views
cheers
Upvotes: 4
Reputation: 43298
The best way is probably to create a method in your application controller and declare it a helper method. Then you can call that method in application.html.erb. For example if you want to be able to use the current user throughout your application you'd do something like this:
class ApplicationController
helper_method :current_user
def current_user
@current_user ||= User.find(session[:user_id])
end
end
Then in application.html.erb you can do the following:
Hello <%= current_user.name %>
It's also possible to use before_filter
like to other answers suggest, but in this solution the database only gets hit when it's necessary. With before_filter
it always gets hit.
Upvotes: 1
Reputation: 11967
you can put method in the application controller
before_filter :load_data
def load_data
@data = Data.all
end
All controllers inherits ApplicationController, so data will be loaded at all actions. Now you can use @data
at you application.html.erb file
Upvotes: 1