我创建了一个API-Only 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):
答案 0 :(得分:3)
因此,我能够在运行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!
在rails日志中,我明白了:
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
打印在日志中。
答案 1 :(得分:0)
如果您使用的是ActionController::API
(并且在实现API时应该使用),则可以通过包含专用的mixin来利用应用程序帮助程序:
class Api::V1::ApiController < ActionController::API
include ActionController::Helpers
helper MyHelper
end
答案 2 :(得分:0)
完整示例:
at:app/controllers/admin_controller.rb
class AdminController < ActionController::API
include ActionController::Helpers
helper AdminHelper
def index
test = ApplicationController.helpers.test('test')
render json: test
end
end
at:app/helpers/admin_helper.rb
module AdminHelper
def test(args)
return args
end
end
您可以使用rails generate rspec:helper
生成测试
RSpec.describe AdminHelper, type: :helper do
it "return args" do
expect(helper.args('yo'))
.to eq('yo')
end
end