みずぎわブログ

技術系のことや日々に考えたことを書き連ねます

Rails application.html.erbにて変数を使う方法

 

Railsにおいてapplication.html.erbや_header.html.erbにて@current_user等の変数を用いたい場面があると思う.

直感的にはapplication_controller.rbにて何かすればいいように思うが,application.html.erbに対応するアクションもわからないし,どうすればよいのか悩むと思う.

その解決法は

 

http://stackoverflow.com/questions/6920897/ror-making-a-variable-available-to-application-html-erb-so-it-is-in-all-views-on

に書いてある.

 

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

 

before_filterを使えばいい

 

これで_headerとかもok

 

こうすればすべての場面で変数を使用することができる.