I created a API-Only Rails Application but I need a administrative area to manage data. So I created this controller:
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 I can't access Helper, even requiring the module. Look a Helper:
module AdminHelper
def teste
'ok'
end
end
And the error generated:
ActionController::RoutingError (uninitialized constant AdminController::AdminHelper):
So, I was able to make this work in a new application running rails new my_api_test_app --api
and then including the below files. I don't think you need the require statements in the controller. You can just include the helper as you've done. I've included the file structure location that I used for each file (notably, I put the helper in app/helpers/admin_helper.rb
, which may be what you need for file to load properly.
#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!
And in the rails log, I get this:
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)
Note that tests are really fun
printed in the log.
If you are using ActionController::API
(and you should when implementing APIs), you can make use of application helpers by including the dedicated mixin :
class Api::V1::ApiController < ActionController::API
include ActionController::Helpers
helper MyHelper
end
Full example:
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
you can use rails generate rspec:helper
to generate test
RSpec.describe AdminHelper, type: :helper do
it "return args" do
expect(helper.args('yo'))
.to eq('yo')
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.