How to Add Images in Rails

Jeffrey Martinez
2 min readJan 31, 2021

--

One of the issues I faced with creating a Rails project was how can I render an image within my views. Turns out Rails has a way to insert an image by using image tag. This blog will show you where to put your images and how to invoke them in your views, so they can be visible to the user.

Where to insert your images?

Images will be inserted within your images folder within your assets directory, example below:

(Do not put them in your “public/img” directory.)

In my case, I created a new directory named “students” to separate my images that I will be using for the views.

Views

Within APIDock documentation, Rails has a unique way on how we can use asset tag helpers to add an image to our views. Check this stackoverflow on how to convert a img src= to an image_tag .

Let’s just say we have a logo.jpeg in our assets/images/students directory.

How can I use an image_tag to include an image in my views? Take a look below:

<%= image_tag("students/logo.jpeg")

If we wanted to add some styling within the image_tag, you would have to invoke them within the parenthesis, like this:

<%= image_tag(“students/logo.jpeg”, width: ‘175px’)

You also want to make sure that you are in the correct directory. The image_tag will know that you are in the assets/images, but it will not know that if you have different directories inside there, in our case we have a “students” directory containing the logo.jpeg

--

--

Jeffrey Martinez

I am a graduate from Flatiron School for Software Engineer. Studied HTML, CSS, Ruby, Ruby on Rails, JavaScript, React, Redux, Sinatra, and Sqlite3