RoR makes the variable available to application.html.erb, so it is present in all header views

I have a variable that I want to get in my application.html.erb application so that it is accessible to all views. I know that I can log in and add it to each controller and add it to each function so that it is available for indexing, display, etc. However, this is crazy. If I want it in the header, I must have access to it in the application.html.erb file so that it is in all of my views. An example of one of my controllers in which it works ...

def index if session[:car_info_id] @current_car_name = current_car.name end respond_to do |format| format.html # index.html.erb format.xml { render :xml => @miles } end end 

Here is my function in applicationcontroller:

  private def current_car CarInfo.find(session[:car_info_id]) end 

If I try to add @current_car_name = current_car.name to my application controller so that the variable is available for my .html.erb application, it will bomb with a Routing to current_car error. I know that the function works, because if I call it in another controller, it works fine, and I can access the variable created in this index view, or something else. You just need to know how to call the function once and have a variable available to all views, since it will be in my header. I could put the information in a session variable, but I read somewhere where you should restrict the session variables to identifiers and generate other necessary information from these identifiers.

Thanks in advance,

+6
source share
1 answer

Just add such a line to your application_controller.rb file and you will have access to current_car in your views.

 helper_method :current_car 

If you really need an instance variable, you can place before_filter in your application as follows. Then both your controllers and views will have access to the variable @current_car .

 class ApplicationController < ActionController::Base before_filter :get_current_car def get_current_car @current_car = CarInfo.find(session[:car_info_id]) end end 
+11
source

Source: https://habr.com/ru/post/894157/


All Articles