2017-02-15 78 views
2

我創建了一個僅限API的Rails應用程序,但我需要一個管理區域來管理數據。所以我創建了這個控制器:如何將Helpers添加到僅限API的Rails應用程序

require 'rails/application_controller' 
require_relative '../helpers/admin_helper' 
class AdminController < Rails::ApplicationController 
    include AdminHelper 
    def index 
    @q = Promotion.search(params[:q]) 
    @promotions = @q.result(distinct: true).page(params[:page]).per(30) 
    render file: Rails.root.join('app', 'views', 'admin', 'index.html') 
    end 
end 

Bot我不能訪問Helper,甚至需要模塊。看一個助手:

module AdminHelper 
    def teste 
    'ok' 
    end 
end 

而產生的錯誤:

ActionController::RoutingError (uninitialized constant AdminController::AdminHelper): 

回答

2

所以,我能夠建立一個新的應用程序這項工作運行rails new my_api_test_app --api,然後包括以下文件。我不認爲你需要控制器中的require語句。你可以像你所做的那樣包含助手。我包括我用於每個文件(特別是文件結構中的位置,我把幫手app/helpers/admin_helper.rb,這可能是你所需要的文件,以正常加載。

#app/controllers/admin_controller.rb 
class AdminController < Rails::ApplicationController 
    include AdminHelper 
    def index 
    test 
    render file: Rails.root.join('app', 'views', 'admin', 'index.html') 
    end 
end 


#app/helpers/admin_helper.rb 
module AdminHelper 
    def test 
    puts "tests are really fun" 
    end 
end 

#config/routes 
Rails.application.routes.draw do 
    root 'admin#index' 
end 

#index.html.erb 
Hello World! 

而且在軌登錄,我得到這樣的:

app/controllers/admin_controller.rb:5:in `index' 
Started GET "/" for 127.0.0.1 at 2017-02-15 15:26:32 -0800 
Processing by AdminController#index as HTML 
tests are really fun 
    Rendering admin/index.html.erb within layouts/application 
    Rendered admin/index.html.erb within layouts/application (0.3ms) 
Completed 200 OK in 8ms (Views: 8.0ms | ActiveRecord: 0.0ms) 

注意tests are really fun印刷在日誌中

+0

還真管用,非常感謝! –

相關問題