控制器的所有操作具有相同的实例变量

发布于 2025-01-06 19:38:37 字数 317 浏览 0 评论 0原文

我有一个 Rails 控制器,定义了两个操作:indexshow。 我在 index 操作中定义了一个实例变量。代码如下:

def index
  @some_instance_variable = foo
end

def show
  # some code
end

How can I access the @some_instance_variable in show.html.erb template?

I have a rails controller with two actions defined: index and show.
I have an instance variable defined in index action. The code is something like below:

def index
  @some_instance_variable = foo
end

def show
  # some code
end

How can I access the @some_instance_variable in show.html.erb template?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青朷 2025-01-13 19:38:37

您可以使用 before 过滤器为多个操作定义实例变量,例如:

class FooController < ApplicationController
  before_filter :common_content, :only => [:index, :show]

  def common_content
    @some_instance_variable = :foo
  end
end

现在可以从 index渲染的所有模板(包括部分模板)访问 @some_instance_variable >显示操作。

You can define instance variables for multiple actions by using a before filter, e.g.:

class FooController < ApplicationController
  before_filter :common_content, :only => [:index, :show]

  def common_content
    @some_instance_variable = :foo
  end
end

Now @some_instance_variable will be accessible from all templates (including partials) rendered from the index or show actions.

拒绝两难 2025-01-13 19:38:37

除非您从 index 操作渲染 show.html.erb,否则您还需要在 show 操作中设置 @some_instance_variable 。当调用控制器操作时,它会调用匹配的方法 - 因此在使用 show 操作时不会调用 index 方法的内容。

如果您需要在 indexshow 操作中将 @some_instance_variable 设置为相同的内容,正确的方法是定义另一个方法,称为通过 indexshow 设置实例变量。

def index
  set_up_instance_variable
end

def show
  set_up_instance_variable
end

private

def set_up_instance_variable
  @some_instance_variable = foo
end

如果您有通配符路由(即 match ':controller(/:action(/:id(.:format))),则将 set_up_instance_variable 方法设为私有可防止将其作为控制器操作调用)')

Unless you're rendering show.html.erb from the index action, you'll need to set @some_instance_variable in the show action as well. When a controller action is invoked, it calls the matching method -- so the contents of your index method will not be called when using the show action.

If you need @some_instance_variable set to the same thing in both the index and show actions, the correct way would be to define another method, called by both index and show, that sets the instance variable.

def index
  set_up_instance_variable
end

def show
  set_up_instance_variable
end

private

def set_up_instance_variable
  @some_instance_variable = foo
end

Making the set_up_instance_variable method private prevents it from being called as a controller action if you have wildcard routes (i.e., match ':controller(/:action(/:id(.:format)))')

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文