如何在仅API的Rails应用程序中添加Helpers

问题描述 投票:2回答:3

我创建了一个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

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

module AdminHelper
  def teste
    'ok'
  end
end

并产生错误:

ActionController::RoutingError (uninitialized constant AdminController::AdminHelper):
ruby-on-rails ruby-on-rails-5
3个回答
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打印在日志中。


2
投票

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

class Api::V1::ApiController < ActionController::API
  include ActionController::Helpers
  helper MyHelper
end

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
© www.soinside.com 2019 - 2024. All rights reserved.