Integrating Bootstrap on Rails
31 May 2017Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first web sites. In this tutorial, I'll show you how to integrate Bootstrap on your Rails application. This tutorial is not for learning Bootstrap, if you want to learn Bootstrap, I recommend you visit this link.
Demo app
I'll create a new rails app to demonstrate how to integrate Bootstrap on Rails. The source code can be downloaded here. If you already have an existing application, you may want to skip some sections and jump straight to integrating bootstrap.
Create a new rails app.
Install the gems with the command below.
Scaffold a post with attributes name and description and run a migration.
Run the rails app with command below.
Visit localhost:3000/posts/new on your browser to see how your rails app looks without Bootstrap.
Apply Bootstrap on views
To keep the scope of this tutorial small, I'll just demonstrate using Bootstrap classes on the form. Below is an example of a form using Bootstrap.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!-- app/views/posts/_form.html.erb -->
<div class="container">
<%= form_for(post) do |f| %>
<% if post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class:"form-control", type:"text" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_field :description, class:"form-control", type:"text" %>
</div>
<div class="actions">
<%= f.submit "Submit", class:"btn btn-primary btn-block" %>
</div>
<% end %>
</div>
The form is wrapped inside the div tag at line 2 with a container class which is a class from Bootstrap. On line 16 and 21 it is using form-group instead of the default field. On line 18 and 23 the text_field uses form-control class. On line 27 the button uses btn btn-primary btn-block class. I've already added the classes for Bootstrap but it still won't look like the way I want it because I still haven't integrated Bootstrap.
Integrating Bootstrap.
Add these lines to the Gemfile.
Install these gems by executing the command below.
Add these lines to the application.scss and make sure bootstrap-sprockets is imported before bootstrap for the icon fonts to work. You have to rename application.css to application.scss
Add this line to the application.js and make sure that //= require_tree . is the last to be required.
The contents of the application.js should be similar to the code below.
Visit localhost:3000/posts/new on your browser to see how your rails app looks with Bootstrap.