Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 api only app with home page

I have generated a rails 5 api application. But I want my app with home page. For that I generated a home controller and added view file i respective views/home/index.html.erb

But when I tried accessing it I am getting below response

Started GET "/home/index" for 127.0.0.1 at 2016-07-14 11:14:03 +0530 Processing by HomeController#index as HTML Completed 204 No Content in 0ms

Started GET "/home/index.js" for 127.0.0.1 at 2016-07-14 11:14:20 +0530 Processing by HomeController#index as JS Completed 204 No Content in 0ms

But I could not see index page content displayed on the web.

Kindly share your thoughts.

like image 653
kotu b Avatar asked Jul 14 '16 05:07

kotu b


1 Answers

I was in the same boat, trying to do a Rails 5 API app that could still bootstrap from a single html page (taken over by JS on load). Stealing a hint from rails source, I created the following controller (note that it's using Rails' instead of my ApplicationController for this lone non-api controller)

require 'rails/application_controller'

class StaticController < Rails::ApplicationController
  def index
    render file: Rails.root.join('public', 'index.html')
  end
end

and put the corresponding static file (plain .html, not .html.erb) in the public folder. I also added

get '*other', to: 'static#index'

at the end of routes.rb (after all my api routes) to enable preservation of client-side routing for reloads, deep links, etc.

Without setting root in routes.rb, Rails will serve directly from public on calls to / and will hit the static controller on non-api routes otherwise. Depending on your use-case, adding public/index.html (without root in routes.rb) might be enough, or you can achieve a similar thing without the odd StaticController by using

get '*other', to: redirect('/')

instead, if you don't care about path preservation.

I'd love to know if anyone else has better suggestions though.

like image 125
Risto Keravuori Avatar answered Nov 19 '22 11:11

Risto Keravuori