Steps to Add Images Using Assets
Step 1: Now, we’ll add an image to the project. You can use any image you want. For example, let’s say we have an image named ‘w3wiki.png’. Place this image file in the ‘app/assets/images’ directory of your Rails project.
Step 2: To display the image, Open the ‘app/views/images/index.html.erb’ file and add the following lines.
<h1>w3wiki</h1>
<%= image_tag(“w3wiki.png”) %>
Step 3: Start the server using below command and open “http://localhost:3000/” in your browser.
rails server
Output:
How to Add Image in Ruby on Rails?
In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline.
Steps on How to Create a Project
Step 1: Create a demo project using the command below. It will create a project named ‘myapp’ in the current directory. Then use the second command to get into your project directory.
rails new myapp
cd myapp
Step 2: Now, we will create a controller and view using the following command. This command creates a controller file named ‘images_controller.rb’ in ‘app/controllers’ and its view file ‘index.html.erb’ in ‘app/views/home’. This command also creates a route file ‘config/routes.rb’.
rails generate controller Images index
Step 3: To display our index page, make changes in the ‘config/routes.rb’ file. Adding the following line in the file will set our index page as root.
Rails.application.routes.draw do
root ‘images#index’
end
Contact Us