[英]Ruby on rails: How can I get values from a database in application.html.erb?
How can I get values from database in application.html.erb?如何从 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?
如何将值传递给 application.html.erb?
Is there anything like beforeRender?有没有类似 beforeRender 的东西? Is there anything like appcontroller.rb to override actions?
有没有类似 appcontroller.rb 的东西来覆盖操作?
You could use an application wide before_filter
- like so您可以使用应用程序范围的
before_filter
- 像这样
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 @var
然后将在您的所有视图中可用
cheers干杯
you can put method in the application controller您可以将方法放入应用程序 controller
before_filter :load_data
def load_data
@data = Data.all
end
All controllers inherits ApplicationController, so data will be loaded at all actions.所有控制器都继承 ApplicationController,因此将在所有操作中加载数据。 Now you can use
@data
at you application.html.erb file
现在您可以在
application.html.erb file
中使用@data
The best way is probably to create a method in your application controller and declare it a helper method.最好的方法可能是在您的应用程序 controller 中创建一个方法并将其声明为辅助方法。 Then you can call that method in application.html.erb.
然后您可以在 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:然后在 application.html.erb 中您可以执行以下操作:
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.也可以像其他答案所建议的那样使用
before_filter
,但在此解决方案中,数据库仅在必要时才会受到影响。 With before_filter
it always gets hit.使用
before_filter
它总是会被击中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.