如何在仅 API Rails 应用程序中添加助手

Lui*_*lho 4 ruby-on-rails ruby-on-rails-5

我创建了一个仅 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
Run Code Online (Sandbox Code Playgroud)

机器人我无法访问 Helper,甚至需要该模块。看个帮手:

module AdminHelper
  def teste
    'ok'
  end
end
Run Code Online (Sandbox Code Playgroud)

并生成错误:

ActionController::RoutingError (uninitialized constant AdminController::AdminHelper):
Run Code Online (Sandbox Code Playgroud)

Ghi*_*his 6

如果您正在使用ActionController::API(并且在实现 API 时应该这样做),您可以通过包含专用 mixin 来使用应用程序助手:

class Api::V1::ApiController < ActionController::API
  include ActionController::Helpers
  helper MyHelper
end
Run Code Online (Sandbox Code Playgroud)


Jam*_*ani 5

因此,我能够在运行的新应用程序中完成这项工作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!
Run Code Online (Sandbox Code Playgroud)

在 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)
Run Code Online (Sandbox Code Playgroud)

注意tests are really fun打印在日志中。