ruby - 在ror中正确的将变量传到view的做法是怎么的?
黄舟
黄舟 2017-04-21 11:17:50
0
4
737

初学ruby,ror中生成了一个controller和view,代码如下:

class MyController < ApplicationController
  def index
    @output="123"
  end
end

我的问题是,为什么变量必须加上AT才能传入view?如果去掉AT,就会报错,AT是什么关键字还是框架约定?什么原理?如果可以请告诉我通识的写法,谢谢

也许这个问题太无聊,但我不太清楚该如何描述,所以也没有搜索到相关信息。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(4)
巴扎黑

@var in Ruby is an instance variable, which can be accessed in all methods of the class; for variables that do not contain @, their scope is within the current method.

ROR is to render the template by calling another method after the current method is executed. In this way, the most convenient way to pass variables between two methods is to use instance variables. If you use ordinary variables and exceed the scope, an error will naturally be reported.

Ty80

Variables starting with @ are instance variables in Ruby. In contrast, variables starting with @@ are class variables.
In Rails, data is passed between controllers and views through instance variables. This procedure is default and does not need to be passed explicitly.

Just remember this rule.

Peter_Zhu

@ in Ruby is equivalent to self in Python

黄舟

Use variables starting with @ as instance variables.
In your scenario, when you initiate an http request, the rails routing mechanism matches the index method of MyController for response.
So the following things will happen:
1. Initialize a MyController instance and execute the index method.
2. Set the instance variable @output of the controller to '123'.
3. Since you did not specify any render specifically, index.html.erb will be rendered by default
4. Copy all instance variables of the controller (removing some that should not be copied)
5. Instantiate a view and set the instance variables just copied from the controller to the view.
6. In this way, you can get this instance variable in the view.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template