2013-11-21 80 views
2

我在app/controllers/api/v1中有一個控制器Api::V1::UsersController。 我在app/helpers/api/v1中有一個幫手模塊Api::V1::ErrorHelperRails Namespaced Helper

我想訪問控制器內的幫助模塊的方法。於是,我打電話給控制器的輔助方法,傳遞模塊:

class Api::V1::UsersController < ApplicationController 

    helper Api::V1::ErrorHelper 

    #other code 
end 

但是,當我訪問控制器內部的輔助方法(respond_with_error)一個我得到以下異常:

undefined method `respond_with_error' for #<Api::V1::UsersController:0x007fad1b189578> 

哪有我從控制器訪問這個幫手?

(我正在使用Rails 3.2)

謝謝。

回答

5

助手在視圖中混合,而不是在控制器中混合。例如,如果您有以下助手

module Authentication 
    def current_user 
    # ... 
    end 
end 

,你包括在任何控制器

helper Authentication 

從動作調用current_user將引發一個未定義的方法錯誤。

如果您想使某些方法可用於視圖和控制器,則需要採用不同的方法。定義方法並將模塊作爲普通模塊包含在內。

class MyController < ApplicationController 
    include Authentication 
end 

並使這些方法成爲助手。

class MyController < ApplicationController 
    include Authentication 

    helper_method :current_user 
end 

您還可以利用included掛鉤。

class MyController < ApplicationController 
    include Authentication 
end 

module Authentication 
    def self.included(base) 
    base.include Helpers 
    base.helper Helpers 
    end 

    module Helpers 
    def current_user 
    end 
    end 
end 
2

helper在您的視圖中包含該模塊,將其包含在您的控制器中僅包含「Api :: V1 :: ErrorHelper」。但是在控制器中包含視圖助手並不是一個好主意,你應該把它放在其他地方(你的lib目錄,也許),而不是稱它爲助手,因爲它不是視圖助手,而是控制器幫手。