rails: use ruby in public/index

3.5k views Asked by At

I'd like to use ruby in my public index.html (e.g. for the stylesheet or a form). But I can't figure out how to do this :S

If I rename it to index.html.erb or index.erb it's not recognized by rails. instead my root from the routes is used (which is part of the app and needs the user to be logged in).

4

There are 4 answers

0
Orlando On BEST ANSWER

Anything in the public directory is rendered as a static asset, so no Ruby code in there.

Instead, you should remove the index.html file in that directory, and replace it with something else within your app. For example, you can do something like this:

# app/controllers/site_controller.rb
class SiteController < ApplicationController
  def index
    # ...
  end
end

# config/routes.rb
root to: 'site#index'

# app/views/site/index.html.erb
<!-- Your HTML and Ruby here -->

This will give you the behavior you want.

0
Albert.Qing On

In your controller

def home
 @datas = Datas.all
 render :file => 'public/index.html'
end
0
medBouzid On

You can't setup root to: .... in your routes file and public/index.html page at the same time, if you use root in your routes.rb file this means you should remove index.html from the public directory, so just you need in your view for the root path to test if the user is logged in ? if yes : show him some content, if not show him other content. hope this help you

note : the PUBLIC directory is used to render static pages without any ruby code inside, this means when you request for a page from the public directory it never call the rails server to interpret it, so you can't added .erb extension .

1
Marek Lipka On

You should generate proper controller and view (with extension html.erb). You should also remove index.html from public folder and tell Rails router (by modifying config/routes.rb) to use your controller on root, for example:

root to: 'home#index'