渲染 erb 模板时出现问题 [ruby]
我正在阅读有关实例变量的旧教程。
但是我无法从控制器调用实例变量到视图。
代码是:
VIEW :
<html>
<head>
<title> title </title>
</head>
<body>
<p> line 1 </p>
<p> <%= @text %> </p>
</body>
</html>
CONTROLLER:
class MoviesController < ApplicationController
def movies
@text = "movietitle"
end
end
当我加载页面时,它只显示第 1 行段落。
我如何调用实例变量@TEST?
Im reading an old tutorial about instance variables.
However i wasnt able to call de instance variable from the CONTROLLER to the VIEW.
The code is:
VIEW :
<html>
<head>
<title> title </title>
</head>
<body>
<p> line 1 </p>
<p> <%= @text %> </p>
</body>
</html>
CONTROLLER:
class MoviesController < ApplicationController
def movies
@text = "movietitle"
end
end
When i load the page, it only shows the line 1 paragraph.
How can i call the instance variable @TEST?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@test
变量应包含"movietitle"
,并且应正确打印这两个段落。也许额外的空间(因为漂亮的印刷)把事情搞砸了?尝试:
编辑:
对于您所展示的内容,您的控制器方法必须命名为
index
而不是movies
The
@test
variable should contain"movietitle"
, and it should properly print both paragraphs.Maybe the extra space (because of pretty printing) is screwing things up? Try:
EDIT:
for what you showed, your controller method must be named
index
notmovies
好的,根据您的视频,这是您的问题。
您向电影添加了一个名为 newaction 的新控制器方法。在浏览器中,您转到 /movies,它有效地调用电影的控制器方法索引并呈现电影的index.hmtl.erb。在index.html.erb中,您尝试获取在newaction中声明的变量,这是另一个完全不同的操作,当然newaction中的任何内容都无法从索引视图访问。
最大的问题是您似乎认为控制器方法就像从视图调用的函数,但事实并非如此。
阅读以下内容: http://guides.rubyonrails.org/routing.html
paths.rb 中的代码如下所示。
如果你执行这些操作并转到 /movies/newaction 并在 newaction.html.erb 中显示标题,它将起作用。
Ok based on your video, here is your problem.
You add a new controller method to movies called newaction. In your browser you go to /movies which effectively, calls the controller method index for movie and renders the index.hmtl.erb for movies. Inside index.html.erb you try to get the variable you declared in newaction, this is another completely different action and of course anything in newaction is not accesible from the index view.
The biggest problem is you seem to think controller methods are like functions which are called from view, they are not.
Read this: http://guides.rubyonrails.org/routing.html
The code in routes.rb will look like.
if you do these and you go to /movies/newaction and inside newaction.html.erb display the title, it will work.