【发布时间】:2020-04-04 23:09:05
【问题描述】:
我收到此错误,但我无法弄清楚如何解决此问题。 最初它只是一个休息 api,但现在我决定也添加一个前端,所以我添加了 'slim-rails' gem 并尝试为我的 Companies_controller 创建前端,但我'我遇到了这个错误,如果我请求 JSON,它工作正常,但由于某种原因它找不到模板,我得到“Api::V1::CompaniesController#index is missing a template for request formats: 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
项目结构
【问题讨论】:
-
向 API 应用程序添加前端只是各种倒退。如果您已经拥有 API,那么更好的选择是使用 SPA 框架(如 React、Vue、Ember、Angular 等)来构建使用您的 API 的前端。
-
向现有的“经典”应用程序添加 API 已经很常见了,但您所做的就像是附上一匹马来拉你的车。
-
错误消息将包含 Rails 正在寻找的文件位置序列和文件格式序列。检查它并将其发布在您的问题中。
标签: ruby-on-rails ruby slim-lang