繁体   English   中英

如何在Rails中使实例变量可用于application.html.erb文件?

[英]How do you make an instance variable available to the application.html.erb file in Rails?

我遇到一种情况,我想在Rails应用程序的所有视图中使用某个方法中的实例变量,而我想知道这样做的“导轨”方法是什么。

如果遇到这种情况,我的subscriptions_controller.rb有以下代码:

def index
    @subscriptions = current_user.subscriptions
end

我该怎么做才能将该实例变量提供给我的application.html.erb 我尝试这样做,但是不起作用:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def index
    @subscriptions = current_user.subscriptions
  end
end

@subscriptions实例变量为nil,我不太清楚为什么。 在Rails中执行此操作的最佳方法是什么?

谢谢!

尝试在ApplicationController使用before_filter设置实例变量:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_filter :set_subscriptions

  def set_subscriptions
    return if current_user.nil?
    @subscriptions ||= current_user.subscriptions
  end
end

暂无
暂无

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

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