视图调用方法时未定义的局部变量或方法

时间:2011-06-08 22:38:03

标签: ruby-on-rails undefined

我正在尝试向我的用户发送“欢迎消息”:

 #welcome_controller.rb
    class WelcomeController < ApplicationController
      def hi
        @current_user
        if (@current_user)
          @welr = '¡Bienvenido' + current_user + ' a nuestra web!' 
        else
          @weli = "¡Bienvenido invitado, no dude en registrarse!"
        end
      end
    end
 #hi.html.erb Only the call
    <%= hi %>

当我初始化我的服务器时,控制器会给我这样的信息:

  

未定义的局部变量或方法`hi'代表

我已经尝试过很多修复这个的方法,但我不能。

3 个答案:

答案 0 :(得分:2)

您需要在控制器中将hi定义为helper_method。像

这样的东西
class WelcomeController < ApplicationController
  helper_method :hi

  def hi
    # your stuff here...
  end

有关详细信息,请参阅http://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method

答案 1 :(得分:2)

这不是你如何使用控制器方法。在Rails中,控制器上定义的方法用于“设置”特定视图所需的数据,或处理给定的请求。它们不应该被视图直接调用。

对于您要执行的操作,您需要向WelcomeHelper添加辅助方法。因此,假设您希望http://yourapp.dev/welcome/输出上述消息,这就是您所需要的:

# app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
  def index
    # Explicitly defining the `index` method is somewhat redundant, given
    # that you appear to have no other logic for this view. However, I have
    # included it for the sake of example.
  end
end    

# app/views/welcome/index.html.erb
<%= greeting %>

# app/helpers/welcome_helper.rb
class WelcomeHelper
  # All methods in WelcomeHelper will be made available to any views
  # that are part of WelcomeController.
  def welcome
    if (@current_user)
      # You may need to change this to something like `@current_user.name`,
      # depending on what @current_user actually is.
      '¡Bienvenido' + @current_user + ' a nuestra web!' 
    else
      "¡Bienvenido invitado, no dude en registrarse!"
    end
  end
end

答案 2 :(得分:1)

本文可能对您有所帮助: Ruby on Rails: Accessing Controller Methods from Your View

只需写下:

<% @controller.hi %>