Xaxum
Xaxum

Reputation: 3675

RoR making a variable available to application.html.erb so it is in all views on a header

I have a variable I want to access in my application.html.erb so it is available to all views. I know I can go in and add it to each controller and add it to each function so it is available to index, show, etc. However, that is crazy. If I want it to be in a header I should be able to access it in the application.html.erb file so it is in all my views. An example of one of my controllers it is working in...

     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 applicationcontroller so the variable is available to my application.html.erb it bombs with a Routing to current_car error. I know the function works because if I call it in a different controller it works fine and I can access the variable produced in that index view or whatever. Just need to know how to call the function once and have the variable accessible to all views since it will be in my header. I could put the information in a session variable but I read somewhere you should limit session variables to ids and generate the other needed information from those ids.

Thanks in advance,

Upvotes: 6

Views: 5743

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

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

helper_method :current_car

If you really wanted an instance variable, you could put a before_filter in your application as follows. Then both your controllers and views will have access to the @current_car variable.

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

Upvotes: 11

Related Questions