在Ruby on Rails中出现未定义的本地变量/无方法错误

5
有人能解释一下为什么我会遇到这个错误吗?Rails 的设计理念是约定优于配置。在下面的代码中,有没有更加符合约定的方式来实现我的目标?
undefined local variable or method `hello_world' for #<#<Class:...>:...>

这里是我的文件:
欢迎控制器(welcome_controller.rb)
class WelcomeController < ApplicationController
  def hello_world
    "Hello, World"
  end
end

welcome/index.html.erb

<%= hello_world %>

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'
  root 'welcome#index'
end

你有什么问题? - sawa
1
你有没有完成过一本Rails教程? - lurker
如何在视图中调用控制器方法?建议: - Arup Rakshit
我按照Rails的入门指南和Code School的Rails for Zombies课程进行学习,但我仍然感到困惑。我本以为我做得很正确。 - TyLeisher
5个回答

7
或者按照以下方式操作:
class WelcomeController < ApplicationController
 helper_method :hello_world
 def hello_world
    "Hello, World"
 end
end

现在在视图中调用它:
<%= hello_world %>

阅读helper_method

将控制器方法声明为助手,以使hello_world控制器方法可用于视图。


1
只是为了明确,因为我不太理解...如果我想做一个基本的hello world而不使用helper_method,我应该只创建一个类,并在类中给出hello_world吗?现在正在阅读helper_method,但不确定为什么需要它。 - TyLeisher

4
你可以使用一个助手(helper),以便在ERB中编写此内容:
module WelcomeHelper

  def hello_world
     "Hello, World"
  end

end

现在,你的ERB应该可以工作了:

<%= hello_world %>

只有当 OP 想要在 Controller 中访问 hello_world 时,才需要在 Controller 中包含 WelcomeHelper。 - Kirti Thorat
@UriAgassi 你需要在控制器内使用 helper WelcomeHelper。这样做可以使答案完整,以便未来的读者不需要去文档中搜索它。 - Arup Rakshit

2

hello_world 是在控制器和路由中定义的操作。 您需要在操作中定义变量。这些变量将在视图中可访问。

class WelcomeController < ApplicationController

 # this is action
 def index
    # this is variable
    @hello_world = "Hello, World"
 end

end

# view index.html.erb
# this calls variables defined in action
<%= @hello_world %>

更新1:

如果您将路由定义为welcome#index,在控制器中的动作名称应该是index


1
除非您在“WelcomeController#index”操作中设置变量,否则此方法将无法正常工作。因为OP想要在“index.html.erb”中访问特定的值。请将您的操作名称更改为“index”,而不是“hello_world”。 - Kirti Thorat
@KirtiThorat 实例变量可以在视图中使用,为什么需要将其移动到 #index 中? - Arup Rakshit
因为 OP 正在渲染 index.html.erb 而不是 hello_world.html.erb - Kirti Thorat
@ArupRakshit 请在任何一个Rails应用程序中尝试它,并让我知道它是否适用于您。 - Kirti Thorat

0

这是更符合Rails惯例的写法:

#config/routes.rb
root to: "welcome#index"
resources :welcome

#app/controllers/welcome_controller.rb
Class WelcomeController < ApplicationController
    def index
       #-> will render #app/views/welcome/index.html.erb
    end
end

#app/views/welcome/index.html.erb
Hello World
<%= hello_world %> <!-- Use `@Arup`'s answer to create a helper method -->

0

你可以使用 print 'ff'。这对我来说非常简单有效 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接