use*_*206 10 ruby controller view ruby-on-rails-3 ruby-on-rails-4
我无法将某些原因传递给show视图...
在我的控制器中我简单地说:
def show
render template: "books/show", :resource => "Some text"
end
Run Code Online (Sandbox Code Playgroud)
在我看来,我打印以下内容:
<h1>My local variable text: <%= resource %></h1>
Run Code Online (Sandbox Code Playgroud)
我收到以下消息:
undefined local variable or method `resource' for #<#<Class:0x00000118ebce90>:0x00000118ec3498>
Run Code Online (Sandbox Code Playgroud)
我在控制器中尝试了以下语法:
render template: "books/show", locals: { resource: "Some text" }
render template: "books/show", locals: { resource => "Some text" }
render template: "books/show", :locals => { resource: "Some text" }
render template: "books/show", :locals => { resource => "Some text" }
Run Code Online (Sandbox Code Playgroud)
没有运气......
有线索吗?
谢谢!
这是一个NovelController类,需要加入 app/ controllers/novel_controller.rb.
class NovelController < ApplicationController
def index
@title = 'Shattered View: A Novel on Rails'
end
end
Run Code Online (Sandbox Code Playgroud)
由于这是Novel控制器和索引动作,因此相应的视图在 app/views/novel/index.html.erb
<h1><%= @title %></h1>
Run Code Online (Sandbox Code Playgroud)
输出:
Shattered View: A Novel on Rails
Run Code Online (Sandbox Code Playgroud)
NovelController#index运行后解释视图.以下是视图可以访问和不能访问的内容:
@title,因为它们已经在完成运行NovelController时在对象上定义NovelController#index.@title.首先我想知道为什么你需要这个template:。您在Rails 2.x上吗?如果不是,则:template不再需要该选项。你应该能够与公正相处
render "books/show"
其次,您需要指定模板吗?您要从哪个控制器渲染?如果是BooksController,则您也不需要模板路径,这使得该行仅
render
那还没有变量。现在,我刚刚检查了一个简单的:
render locals: { resource: "Some text" }
以及:
render 'books/show', locals: { resource: "Some text" }
对我有用。也许早期的Rails版本将'resource'视为某种关键字?不知道,但是上面的Worksforme™都是两种形式。
您无法将局部变量从控制器传递到视图。您可以做的是将其定义为实例变量,然后它将自动在视图中可用。
@resource = @book
Run Code Online (Sandbox Code Playgroud)
如果您想传递完全不同的对象,那么只需以不同的方式定义这些实例变量即可。
| 归档时间: |
|
| 查看次数: |
18361 次 |
| 最近记录: |