Xax*_*xum 6 variables ruby-on-rails-3
我有一个我想在我的application.html.erb中访问的变量,因此它可供所有视图使用.我知道我可以进入并将其添加到每个控制器并将其添加到每个功能,以便它可用于索引,显示等.但是,这很疯狂.如果我希望它在标题中,我应该能够在application.html.erb文件中访问它,所以它在我的所有视图中.我工作的一个控制器的例子......
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
Run Code Online (Sandbox Code Playgroud)
这是我在applicationcontroller中的函数:
private
def current_car
CarInfo.find(session[:car_info_id])
end
Run Code Online (Sandbox Code Playgroud)
如果我尝试将@current_car_name = current_car.name添加到我的applicationcontroller中,那么我的application.html.erb就可以使用该变量,它会报告路由到current_car错误.我知道该函数有效,因为如果我在不同的控制器中调用它,它工作正常,我可以访问在该索引视图中生成的变量或其他任何东西.只需要知道如何调用该函数一次并让所有视图都可以访问该变量,因为它将在我的标题中.我可以将信息放在会话变量中,但我读到某处你应该将会话变量限制为id并从这些id生成其他所需信息.
提前致谢,
Dyl*_*kow 11
只需在您的application_controller.rb文件中添加这样的行,即可current_car在您的视图中访问.
helper_method :current_car
Run Code Online (Sandbox Code Playgroud)
如果您真的想要一个实例变量,可以before_filter按如下方式在应用程序中添加一个.然后,您的控制器和视图都可以访问该@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
Run Code Online (Sandbox Code Playgroud)