【问题标题】:Undefined local variable / no method error in Ruby on RailsRuby on Rails 中未定义的局部变量/没有方法错误
【发布时间】:2017-03-04 15:07:17
【问题描述】:

谁能向我解释为什么我会收到这个错误? Rails 是关于约定的。有没有更传统的方式来做我想做的事情?

undefined local variable or method `hello_world' for #<#<Class:...>:...>

这是我的文件:

welcome_controller.rb

class WelcomeController < ApplicationController
  def hello_world
    "Hello, World"
  end
end

欢迎/index.html.erb

<%= hello_world %>

routes.rb

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

【问题讨论】:

  • 你的问题是什么?
  • 你学习过 Rails 教程吗?
  • 更改主题 - 如何在视图中调用控制器方法?..suggestion..
  • 我遵循 Rails 入门指南和僵尸代码学校 Rails,但我仍然感到困惑。我认为我做得对。

标签: ruby-on-rails ruby


【解决方案1】:

或者这样做:

class WelcomeController < ApplicationController
 helper_method :hello_world
 def hello_world
    "Hello, World"
 end
end

现在在视图中调用它:

<%= hello_world %>

阅读helper_method

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

【讨论】:

  • 我很清楚,因为我不太明白......如果我想在没有 helper_method 的情况下做一个基本的 hello world,我应该刚刚创建一个类,并在里面给出 hello_world班上?现在阅读 helper_method,但不知道我为什么需要它。
【解决方案2】:

您可以使用helper 允许您将其写入您的 ERB:

module WelcomeHelper

  def hello_world
     "Hello, World"
  end

end

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

<%= hello_world %>

【讨论】:

  • @UriAgassi 仅当 OP 想要在 Controller 中访问 hello_world 时才需要在控制器中包含 WelcomeHelper。
  • @UriAgassi 您需要在控制器内部使用helper WelcomeHelper。这样做可以使答案完整,这样以后的读者就不需要在文档中搜索它了..
【解决方案3】:

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!

【讨论】:

  • 这将不起作用,除非您在 WelcomeController #index 操作中设置变量。由于 OP 想要访问 index.html.erb 中的特定值。将您的操作名称更改为 index 而不是 hello_world
  • @KirtiThorat 实例变量可以在视图中使用。为什么要在 #index 中移动它?
  • 因为 OP 正在渲染 index.html.erb 而不是 hello_world.html.erb
  • @ArupRakshit 在您的任何 Rails 应用程序中试用它,如果它适合您,请告诉我。
【解决方案4】:

这对你来说更像是 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 -->

【讨论】:

    【解决方案5】:

    您可以使用 print 'ff'。它只是为我工作:)

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多