ruby-on-railsrubyerb

How to set up root route with Rails API?


I created a Rails API with the --api flag.

I want to set up a root route with a custom HTML file.

This is my 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

This is my home_controller.rb:

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

This is my views/home/index.html.erb:

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

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

It seems to direct me to my HomeController#index method, but it is not rendering the <h1>hi</h1> on the browser.

This is my terminal output:

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)

Not sure if I am doing some configuration incorrectly.


Solution

  • For rails-6

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

    For rails 5 its already answered here: Render a view in Rails 5 API