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

Ruby on rails RubyonRails:如何从application.html.erb中的数据库获取值?,ruby-on-rails,Ruby On Rails,如何从application.html.erb中的数据库获取值?我需要得到整个项目的这些值。这些值将永久保留到所有页面。如何将值传递到application.html.erb 有没有类似的东西? 是否有类似appcontroller.rb的方法来覆盖操作?您可以将方法放入应用程序控制器中 before_filter :load_data def load_data @data = Data.all end 所有控制器都继承ApplicationController,因此将在所有操作中加载

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

有没有类似的东西?
是否有类似appcontroller.rb的方法来覆盖操作?

您可以将方法放入应用程序控制器中

before_filter :load_data


def load_data
 @data = Data.all
end

所有控制器都继承ApplicationController,因此将在所有操作中加载数据。现在,您可以在
application.html.erb文件中使用
@data
,您可以将方法放入应用程序控制器中

before_filter :load_data


def load_data
 @data = Data.all
end

所有控制器都继承ApplicationController,因此将在所有操作中加载数据。现在,您可以在
application.html.erb文件中使用
@data
您可以在筛选之前使用应用程序范围的
-如下所示

    class ApplicationController < ActionController::Base
      before_filter :load_application_wide_varibales

      private

      def load_application_wide_varibales
        @var = Model.where :condition => "whatever"
      end
    end
class ApplicationController“无论什么”
终止
终止
@var
将在所有视图中可用


干杯

您可以在筛选之前使用应用程序范围的
——就像这样

    class ApplicationController < ActionController::Base
      before_filter :load_application_wide_varibales

      private

      def load_application_wide_varibales
        @var = Model.where :condition => "whatever"
      end
    end
class ApplicationController“无论什么”
终止
终止
@var
将在所有视图中可用


干杯

最好的方法可能是在应用程序控制器中创建一个方法,并将其声明为helper方法。然后可以在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 %>
你好

也可以像其他答案所建议的那样,在过滤之前使用
,但在这个解决方案中,数据库只在必要时才会被访问。在筛选之前使用
,它总是会被命中。

最好的方法可能是在应用程序控制器中创建一个方法,并将其声明为helper方法。然后可以在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\u filter
时,它总是被命中。

before\u filter?-在过滤器之前-