I have been having issues setting up bootstrap carousels on rails. It took me days before I finally found a way out. At a point, all articles and videos are not helping even after following the whole steps religiously.
Lets’s skip all that and get to work.
Let create a new rails app:
rails new carousels
We wait for rails to finish the app creation.
Once we are done with that, we go into our:
app/assets/stylesheets then rename "application.css" to "application.scss"
Once that is done, let us head over to the bootstrap website and copy the download the carousels sample code to our local system.
Install bootstrap, jquery, and popper.js to our application.
yarn add bootstrap jquery popper.js
Also add the bootstrap link to the head tag of your app/views/layout/application.htm.erb
.
<%= stylesheet_link_tag "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" %>
After that, go to https://getbootstrap.com/docs/5.0/examples/, click on the download examples, then extract the file to your system.
Go into the bootstrap extracted folder and locate the carousel
folder, not carousel-rtl
folder. Open the carousel
folder, copy the carousel.css
file and move it to your application stylesheet folder.
Your app/assets/stylesheets
folder should consist of the application.scss
file and carousel.css file.
Rename:
app/assets/stylesheets/carousel.css to app/assets/stylesheets/carousel.scss
Go into your app/assets/stylesheets/application.scss
and add import the carousel.scss
to it by adding the code below to your application.scss
file:
@import 'carousel';
Also, go into your app/javascripts/packs/application.js
and the import bootstrap.
import 'bootstrap'
We need to generate a view and a controller for our app. We can do that using the scaffold command. Let us generate a “post” view and controller for our app. We can do that by using the command below:
rails generate scaffold post
After that, we need to run migrations on the database for the scaffold command to take effect on the schema:
rails db:migrate
Once that is done, we can start our app by:
rails s
The command above will start the rails server. The next thing is to route the root path of our app to post#index
page.
Go to your config/routes.rb
, add the code:
root to: 'posts#index'
The code below will route our index page localhost:3000
to the post index page.
Next, we go into our index file in the views folder app/views/posts/index.html.erb
to update it to display our carousels.
Let us go back to the carousel folder we downloaded on bootstrap. Go into the folder, open the index.html file and copy the code from:
<div id="myCarousel" class="carousel slide" data-bs-ride="carousel">
..........
..........
</div>
Paste the copied code to your index page and refresh your browser.
Tadaaa!!! Your carousels should work fine now.
I hope this article helps. Suggestions are highly welcomed.