ruby 如何使用Rails API设置根路由?

mqxuamgl  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(83)

我创建了一个带有--api标志的Rails API。
我想用自定义HTML文件设置根路由。
这是我的routes.rb

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :pros
      resources :browsers
      resources :payment_methods
      resources :prosps
      resources :prosp_likes
      resources :prosp_comments
      resources :prosp_images
      resources :recommendations
      resources :recommendation_likes
      resources :recommendation_comments
      resources :recommendation_images      
    end
  end

  root "home#index"
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

这是我的home_controller.rb

class HomeController < ApplicationController
    def index
        render 'home/index'
    end
end

这是我的views/home/index.html.erb

<!DOCTYPE html>
<html>
  <head>
  </head>

  <body>
    <h1>hi</h1>
  </body>
</html>

它似乎指向我的HomeController#index方法,但它没有在浏览器上呈现<h1>hi</h1>
这是我的终端输出:

Started GET "/" for ::1 at 2020-08-24 21:23:18 -0500
Processing by HomeController#index as HTML
Completed 200 OK in 0ms (Views: 0.1ms | ActiveRecord: 0.0ms | Allocations: 104)

我不确定我是否做了一些错误的配置。

hfwmuf9z

hfwmuf9z1#

用于导轨-6

class HomeController < ActionController::Base
  def index
    render render: 'home/index'
  end
end

对于Rails 5,这里已经回答了:Render a view in Rails 5 API

ojsjcaue

ojsjcaue2#

您需要更改HomeController以直接使用rails,因为这将是一个非api控制器:

require 'rails/application_controller'

class HomeController < Rails::ApplicationController
  def index
    render file: 'app/views/home/index.html'
  end
end

路径app/views/home/index.html是视图所在的位置。

相关问题