Techioz Blog

Rails APIでルートルートを設定するにはどうすればよいですか?

概要

–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 メソッドに誘導されているようですが、ブラウザ上に

hi

が表示されません。

これは私の端末出力です:

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)

設定が間違っているのかどうかわかりません。

解決策

レール-6用

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

Rails 5 については、すでにここで回答されています: Rails 5 API でビューをレンダリングする