Api :: V1 :: CompaniesController#index缺少请求格式的模板:text / html

问题描述 投票:0回答:1

我遇到此错误,但我一直无法弄清楚该如何解决。最初它只是一个剩余的api,但是现在我决定也添加一个前端,因此我添加了“ slim-rails” gem并尝试为我的companies_controller创建前端。 m卡在此错误中,如果我请求JSON,它可以正常工作,但是由于某种原因,它找不到模板,并且我收到“ Api :: V1 :: CompaniesController#index缺少用于请求格式的模板:text / html ”。我所做的大多数研究都指向错误的名称,但显然一切都很好。这是我的代码:

companies_controller.rb

module Api
    module V1
        class CompaniesController < ApplicationController            
            before_action :set_company, only: [:show, :edit, :update, :destroy]
            #List all
            def index
                # TODO validate and filter based on user role permissions
                @companies = Company.order('active DESC, name')
                respond_to do |format|
                    format.html 
                    format.json { json_response(@companies , status: :ok) }
                end
            end

            #other controller methods

            private

            def set_company
                @company = Company.find(params[:id])
            end

            def company_params
                params.require(:company).permit(:id, :name, :active, :city_id)
            end

        end
    end
end 

routes.rb

Rails.application.routes.draw do
  namespace 'api' do
    namespace 'v1' do
      resources :states, only: :index
      resources :companies
    end
  end
end 

index.html.slim

h1 Listing companies

table
  thead
    tr
      th Name
      th Active
      th City
      th
      th
      th

  tbody
    - @companies.each do |company|
      tr
        td = company.name
        td = company.active
        td = company.city
        td = link_to 'Show', company
        td = link_to 'Edit', edit_company_path(company)
        td = link_to 'Destroy', company, data: { confirm: 'Are you sure?' }, method: :delete

br

= link_to 'New Company', new_company_path

项目结构

Project structure

ruby-on-rails ruby slim-lang
1个回答
2
投票

由于Controller在Api::V1名称空间中,所以Rails将在同一名称空间中寻找视图,这意味着它将在app/views/api/v1/companies/index.html.slim中寻找视图。而且该目录当然不存在。您可以尝试创建该目录并将文件移到那里。

但是,我认为这不是一个好主意。 API控制器应与基于视图的控制器分开。如果您想将所有内容都保留在同一个应用程序中(API和前端两者),建议您创建一个新的Controller来处理根名称空间中的前端,例如app/controllers/companies_controller.rb。然后,该Controller就像一个“普通” Rails Controller一样,而不是特定于API的。

或者您可以像建议的@max一样,只为前端有一个完全独立的应用程序。那将是理想的,但是如果您只是在进行演示/辅助项目,那么现在可能已经过头了。

© www.soinside.com 2019 - 2024. All rights reserved.