2011-06-08 57 views
0

我試圖給一個「歡迎辭」我的用戶與:Undenfined局部變量或方法時,視圖調用一個方法

#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 %> 

當我初始化我的服務器控制器給我這個消息:

未定義的局部變量或方法'喜」的

我試圖修復該許多wways,但我不能。

回答

2

您需要定義爲喜在控制器中helper_method。像

class WelcomeController < ApplicationController 
    helper_method :hi 

    def hi 
    # your stuff here... 
    end 

末的東西

更多信息

+0

謝謝,我將閱讀這份文件。 – Ivanhercaz 2011-06-09 16:03:41

2

這不是你如何使用控制器方法見http://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper_method。在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 
+0

感謝您的回覆並幫助我。 – Ivanhercaz 2011-06-09 16:03:04

相關問題