gpt4 book ai didi

ruby-on-rails - Controller 所有 Action 的相同实例变量

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:47 25 4
gpt4 key购买 nike

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

def index
@some_instance_variable = foo
end

def show
# some code
end

如何访问 show.html.erb 模板中的 @some_instance_variable

最佳答案

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

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

def common_content
@some_instance_variable = :foo
end
end

现在 @some_instance_variable 可以从 indexshow Action 呈现的所有模板(包括部分模板)访问。

关于ruby-on-rails - Controller 所有 Action 的相同实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9330486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com