Using Bootstrap 3 with Rails 4

If you are looking to use Bootstrap 3 with Rails, then this article is for you. It provides a guide to adding Bootstrap 3, aka Twitter Bootstrap 3, to a new Rails 4 project. I found this article from Eric Minkel, however I’ve deviated slightly from his implementation and I decided to document it.

Let’s start by creating a new project:

rails new bootstrap

Next, we need Bootstrap 3 and you can download the latest version here. At the time this article was written, the latest Bootstrap release was v3.0.2.

I’m only interested in using the minimized Bootstrap files. We need to copy a number of files into our project from the Bootstrap download:

  1. Copy bootstrap.min.css to the /vendor/assets/stylesheets directory
  2. Copy bootstrap.min.js to the /vendor/assets/javascripts directory
  3. Copy the fonts directory and its contents to /vendor/assets/

Now that the files have been added to your project. We need to tell the application to use them.

Edit app/assets/stylesheets/application.css and add *= require bootstrap.min along with some @font-face overrides which change the path to the glyphicons. We’ll do that here to avoid changing the bootstrap files.

 *= require bootstrap.min
 *= require_self
 *= require_tree .
 */

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../assets/glyphicons-halflings-regular.eot');
  src: url('../assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), 
       url('../assets/glyphicons-halflings-regular.woff') format('woff'), 
       url('../assets/glyphicons-halflings-regular.ttf') format('truetype'), 
       url('../assets/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

Next, we need to edit app/assets/javascripts/application.js and add //= require bootstrap.min. Here’s a look at mine:

//= require jquery
//= require jquery_ujs
//= require bootstrap.min
//= require turbolinks
//= require_tree .

That is all it takes to add Bootstrap 3 to your rails application without a gem. There is also a sample application on Github, you can download it here.

I also recently published a new article that builds on this project. In it, I show you how to build the Bootstrap jumbotron in Rails. Check it out here.

If you have any suggestions or feedback, please let me know in the comments, via email or on Twitter.

  • Hey, in the application.js file, the “bootstrap.min“ needs to be “required”.

    //= require bootstrap.min

    • rvg.me.admin

      Thanks Tyler! I’ve updated the github repo and post to correct the omission.

    • Thanks for pointing it out!

  • Thanawath.R

    Thank you very much for your tutorial ^_^

  • Pingback: Bootstrap 3 Glyphicon errors | QueryPost.com()

  • Ron Phillips

    This was a big help. The only problem for me: my development environment can’t see the glyphicons. So, since I’m not making a lot of changes to the css or js at this point in my project, I set development.rb environment to use /public/assets instead of the pipeline.

    # — disable on-the-fly compilation
    config.assets.compile = false
    # == Generate digests for assets URLs.
    config.assets.digest = true

    When I make changes, I will either comment these lines out, or run rake assets:precompile again.

    • Hi Ron,

      Thanks for the comment. The glyphicons should always show up in development when stored in vendor. Silly question but did you restart the server? Is your project on github for me to take a quick look? I have posted sample code on github for this post if you wanted to try cloning it to test. The link in the last few paragraphs.

      There are a few steps to make them work in production that I need to add to the article since a few readers have forgotten to precompile as recommended in the RailsGuides here: http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets

  • Just stepped by

    Boy was I spending time on getting these glyphicons to work! Thanks for finally presenting _the_ solution:

    move require_self at bottom so overrides can work … apparently.

    Thanks again!

  • poornima

    Wow I am so happy I stumbled upon this post, very helpful and simple to setup.

  • Bernat Pons

    Congratulations ! I was lost about using correctly Bootsrap in Rails 4. Your article was what i was looking for. A lot of thanks !

  • billybob

    Really want to use this “light” approach.
    I’ve tried many thing – just can’t shift this error in my logs, any tips?

    ActionController::RoutingError (No route matches [GET] “/fonts/glyphicons-halflings-regular.svg”):

    • Hi Billybob,

      Can you check that you made changes to your application.css file outlined near the top of this post AND that you restarted your server.

      If it still isn’t working and it is on github, send me a link and I’ll take a quick look for you.

      Cheers,

      Richard

      • billybob

        Hi Richard, yes, definitely made the changes to application.css to match your notes (just wondering if there is a copy and paste error maybe grabbing a strange character from the web, i am on a mac) restarted the server many times! Not on github unfortunately. Bit strange really, I have the font file in the right place I believe also. here is my application.css

        /*
        * This is a manifest file that’ll be compiled into application.css, which will include all the files
        * listed below. bla bla bla..
        *
        *= require bootstrap.min
        *= require_self
        *= require_tree .
        */

        @font-face {
        font-family: ‘Glyphicons Halflings’;
        src: url(‘../assets/glyphicons-halflings-regular.eot’);
        src: url(‘../assets/glyphicons-halflings-regular.eot?#iefix’) format(’embedded-opentype’),
        url(‘../assets/glyphicons-halflings-regular.woff’) format(‘woff’),
        url(‘../assets/glyphicons-halflings-regular.ttf’) format(‘truetype’),
        url(‘../assets/glyphicons-halflings-regular.svg#glyphicons_halflingsregular’) format(‘svg’);
        }

        //= require rails_bootstrap_forms

        • Steve Castaneda

          Having the same issue. Ever figure this out?

          • James

            I ran into this issue and managed to fix it by adding the following configuration options:

            app.config.assets.paths << Rails.root.join('vendor', 'assets', 'fonts')
            app.config.assets.precompile << /.(?:svg|eot|woff|ttf)$/

            See this comment: https://github.com/thoughtbot/bourbon/issues/239#issuecomment-30830589

            I wish I understood why this didn't work out of the box for me, but the above did the trick.

          • Hi James,

            In production, it is true that you need to do a few extra steps before the deploy. I keep meaning to add an update to the post to include those steps but haven’t found the time to date.

            Did you have any issues in development?

            Richard

          • James

            Re. production I’m deploying to Heroku, so assset precompiling it taken care of automatically.

            I had issues in development initially, which I solved only to have issues in production. In the end it turned out my the application.css asset helpers weren’t working because I was using .css as the extension. Changing .scss fixed this.

            My final set up looked like:

            [application.rb]

            config.assets.paths << Rails.root.join('vendor', 'assets', 'fonts')
            config.assets.precompile << /.(?:svg|eot|woff|ttf)$/

            [application.css.scss]

            @font-face {
            font-family: 'Glyphicons Halflings';
            src: asset_url('glyphicons-halflings-regular.eot');
            src: asset_url('glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
            asset_url('glyphicons-halflings-regular.woff') format('woff'),
            asset_url('glyphicons-halflings-regular.ttf') format('truetype'),
            asset_url('glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
            }

          • Thanks for sharing. One of the common problems these days with this older post is that many people are using SCSS instead of CSS and not changing ‘src: url’ to ‘src: asset-url’. I appreciate that you posted the code, it saves me editing the article for another while!

            I just checked one of my projects and I did:

            [config/environments/production.rb]
            # Include Everything in the Vendor Directory
            config.assets.precompile += [‘vendor/*’]

            # Adding Webfonts to the Asset Pipeline
            config.assets.precompile << Proc.new { |path|
            if path =~ /.(eot|svg|ttf|woff)z/
            true
            end
            }

            For anyone else reading this. To test locally, try the following:

            a. At the console: rails s
            b. Check results in a browser that the glyphicons are working. Open http://localhost:3000
            c. If all looks good, stop the rails server and go to d below. Otherwise let me know
            d. At the console: RAILS_ENV=production bundle exec rake assets:precompile
            e. At the console: rails s -e production
            f. Check results in a browser that the glyphicons are working. Open http://localhost:3000

            If you have problems in production locally, check your Gemfile. It is possible that you have gem 'pg' for a Heroku deploy and don't have Postgres installed locally. If that's the case, temporarily comment out that line.

          • Jan Nowak

            Worked, thx!

          • I did help bullyboy resolve his issue. If it isn’t working in development, my first guess might be that you are using scss instead of css for your bootstrap stylesheet or that you didn’t restart your rails server. If it is the former and you are using scss, try this instead:

            Change ‘src: url’ to ‘src: asset-url’ because we are using scss.

            // Override Bootstrap 3’s font location
            @font-face {
            font-family: ‘Glyphicons Halflings’;
            src: asset-url(‘glyphicons-halflings-regular.eot’);
            src: asset-url(‘glyphicons-halflings-regular.eot?#iefix’) format(’embedded-opentype’),
            asset-url(‘glyphicons-halflings-regular.woff’) format(‘woff’),
            asset-url(‘glyphicons-halflings-regular.ttf’) format(‘truetype’),
            asset-url(‘glyphicons-halflings-regular.svg#glyphicons_halflingsregular’) format(‘svg’);
            }

            If that doesn’t fix it, then give me more details. Are you having the problem in development, test, production or all? Also, can you upload the project somewhere that I can take a quick look?

  • Pingback: New Project Setup – Part 1 | der Programmer()

  • Joon Ho

    OH MY GOD, THIS SOLVED THE GLYPHICON PROBLEM IVE BEEN HAVING FOR SO LONG. A LIFE SAVER. THANK YOU!!!

  • Thank you!

  • I don’t understand how the ‘../assets/’ css part works without having “fonts” in the middle of the path.. but I’m glad it works, the icons were driving me crazy. I liked this solution the best of the ones the stack overflow discussion.

  • mesaroda

    excellent article , thank you.. all morning trying to get the my glyphicons to work…implemented your article and got mine working straight away…finally i can move on with rest my project

  • Adam

    Hello nice article got me working when i put it in vendor/assets. Question, why would I put it in vendor and not in the regular assets folder? and do you remove the @font-face style from the bootstrap.css or leave and also have it the application.css?

  • 亚夫 李

    thanks.

  • I found a another soulution here https://snailing.org/posts/custom-bootstrap-in-rails/, and got this from stackoverflow ; – )

  • Rick Holland

    Thank you very much, after trying 4 other methods on blogs and stackoverflow this one worked the first try.

  • Prasad Surase

    You have specified the relative path of the fonts files in the bootstrap.css. This will work in developement environment but may not work in production because the assets will be precompiled and digested. Also, the precompiled assets will be moved to public/assets. Please confirm.

    • Yes, there are additional steps for a production deploy which was something I didn’t contemplate at the time the article was written. The last time I was asked a similar question, back in January of 2014, I responded with the details below but your mileage may vary. If you use any of the code below, it would be helpful if you could reply letting me know if I missed anything so that future visitors can benefit from your efforts.

      =====

      1. In config/environments/production.rb add the following:

      # Include Everything in the Vendor Directory
      config.assets.precompile += [‘vendor/*’]

      # Adding Webfonts to the Asset Pipeline
      config.assets.precompile << Proc.new { |path|
      if path =~ /.(eot|svg|ttf|woff)z/
      true
      end
      }

      2. In app/assets/stylesheets/bootstrap_and_overrides.css.scss

      Change 'src: url' to 'src: asset-url' because we are using scss.

      // Override Bootstrap 3's font location
      @font-face {
      font-family: 'Glyphicons Halflings';
      src: asset-url('glyphicons-halflings-regular.eot');
      src: asset-url('glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
      asset-url('glyphicons-halflings-regular.woff') format('woff'),
      asset-url('glyphicons-halflings-regular.ttf') format('truetype'),
      asset-url('glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
      }

      3. Test locally at a console and in your browser:

      a. At the console: rails s
      b. Check results in a browser that the glyphicons are working. Open http://localhost:3000
      c. If all good, go to d otherwise let me know
      d. At the console: RAILS_ENV=production bundle exec rake assets:precompile
      e. At the console: rails s -e production
      f. Check results in a browser that the glyphicons are working. Open http://localhost:3000

    • I neglected to mention in my first reply that there is also a comment from James here that has the steps he took that you might want to review.

  • Tainara Santos Reis

    what is “fonts directory”?

    • The folder called fonts is the “fonts directory”. Does that answer your question?

  • Nice tutorial, dude!

    I really love adding bootstrap without using gems. To me, is cleaner.

    Thanks a lot.