gpt4 book ai didi

ruby-on-rails - Rails Controller 中实例变量的作用域是什么?

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

如果我在 Rails Controller 中创建一个实例变量,该实例变量的作用域是什么?它对所有 Rails 应用程序可用,还是仅对与该特定 Controller 关联的 View 和模型可用?由于我是 Rails 的新手,所以我有点困惑。

最佳答案

Rails Controller 中的实例变量有两种使用方式:

  • 它在该 Controller 的实例方法(包括父类(super class)实例方法)中可用,就像任何其他 Ruby 实例变量一样。
  • 当 Rails Controller 操作呈现 View 时, Controller 的实例变量被(浅)复制到 View 实例。 ( View 实例是模板中 self 的值。)因此,在 Action 呈现时定义的 Controller 实例变量在该 Action 的 View 中有效可用。 View 助手只是由 View 实例扩展的模块,因此 Controller 实例变量也可以在 View 助手方法中有效使用。

    请注意,虽然 Controller 实例变量被复制到 View 中,但 View 中定义的实例变量不会被复制回 Controller 。这不是您通常需要发生的事情,因为呈现 View 通常是 Controller 操作中完成的最后一件事。 View 中定义的局部变量在整个 View 中都可用,因此根本没有理由在 View 中定义实例变量。

给定 Controller 中的实例变量在其他 Controller 、其他 Controller 的 View 或任何模型中根本不可用。

关于ruby-on-rails - Rails Controller 中实例变量的作用域是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35828121/

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