繁体   English   中英

Ruby on rails:如何从 application.html.erb 中的数据库中获取值?

[英]Ruby on rails: How can I get values from a database in application.html.erb?

如何从 application.html.erb 中的数据库中获取值? 我需要为整个项目获取这些值。 这些值将永远保留到所有页面。 如何将值传递给 application.html.erb?

有没有类似 beforeRender 的东西? 有没有类似 appcontroller.rb 的东西来覆盖操作?

您可以使用应用程序范围的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然后将在您的所有视图中可用

干杯

您可以将方法放入应用程序 controller

before_filter :load_data


def load_data
 @data = Data.all
end

所有控制器都继承 ApplicationController,因此将在所有操作中加载数据。 现在您可以在application.html.erb file中使用@data

最好的方法可能是在您的应用程序 controller 中创建一个方法并将其声明为辅助方法。 然后您可以在 application.html.erb 中调用该方法。 例如,如果您希望能够在整个应用程序中使用当前用户,您可以执行以下操作:

class ApplicationController
  helper_method :current_user

  def current_user
    @current_user ||= User.find(session[:user_id])
  end
end

然后在 application.html.erb 中您可以执行以下操作:

Hello <%= current_user.name %>

也可以像其他答案所建议的那样使用before_filter ,但在此解决方案中,数据库仅在必要时才会受到影响。 使用before_filter它总是会被击中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM