Categories
ruby-on-rails

Rails Root directory path?

327

How do I get my Rails app’s root directory path?

    580

    In Rails 3 and newer:

    Rails.root
    

    which returns a Pathname object. If you want a string you have to add .to_s. If you want another path in your Rails app, you can use join like this:

    Rails.root.join('app', 'assets', 'images', 'logo.png')
    

    In Rails 2 you can use the RAILS_ROOT constant, which is a string.

    4

    • 3

      In Rails 2.3 Rails.root is an instance of Pathname where RAILS_ROOT is a string.

      – Richard

      Jun 9, 2011 at 9:54

    • 1

      Only Rails.root in 3.1 and later (ahh.. the case of changing CONSTANT ;))

      – thanikkal

      Nov 10, 2011 at 13:35


    • 2

      You can also Rails.root.join(*%w( app assets images logo.png )).

      – Nate

      Aug 12, 2014 at 18:21

    • 18

      Personally I like the newer syntax: Rails.root / 'app' / 'assets' / 'images' / 'logo.png'

      – Ajedi32

      Feb 18, 2016 at 17:13


    111

    For super correctness, you should use:

    Rails.root.join('foo','bar')
    

    which will allow your app to work on platforms where / is not the directory separator, should anyone try and run it on one.

    1

    • 1

      For example, on my MacBook, Rails.root.join('foo','bar') evaluates to Pathname object whose @path is ‘/Users/purplejacket/my_rails_app/foo/bar’

      Sep 7, 2012 at 0:58


    24

    You can access rails app path using variable RAILS_ROOT.

    For example:

    render :file => "#{RAILS_ROOT}/public/layouts/mylayout.html.erb"
    

    1

    • 4

      RAILS_ROOT is deprated since Rails 3.0 insted use Rails.root

      Nov 23, 2017 at 14:55