How to Accept File URLs Coming Back from S3
Now that we know our uploader is working fine, we are going to take the URL sent back to us from the S3 storage engine and render it into an image in the Rails app.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that we know our uploader is working fine, we are going to take the URL sent back to us from the S3 storage engine and render it into an image in the Rails app.

To do that, go to app/views/posts and open a file called show.html.erb. This is how this file looks.

large

Make a change in line #10, so that it has this code:

<%= image_tag(@post.image.url) %>

To test, go to the browser page, and click on the Show link. This should show you the image, and not the URL.

However, this page displays the full size of the image, which is not really what we want for this application. So, we have to resize these images.

If you remember, we created two versions called tiny and profile_size in our photo_uploader.rb file. We are going to use it here. Change the code in line #10 of your show.html.erb file like this:

<%= image_tag(@post.image.profile_size.url) %>

If you refresh the page, you should have a smaller image, typically like this:

large

Now, let's try to understand the code we changed.

If you go back to the file and type @post.inspect, you can see how that record looks in the database.

large

This is interesting because when you had @post.image earlier, it gave the AWS URL, and not what's in the database. This is because we are using CarrierWave and other gems, so they know how to upload this file onto AWS and return a string back.

If you change this code to @post.image.inspect, it gives you the full set of data that is returned from the AWS API.

large

If you look at the URL closely, it gives all the information about CarrierWave, Fog and just about everything else you need. Now, look for the profile_size variable in that long URL, and you'll find it right after the @path variable. So, we know we have access to this profile_size method, and we can use it inside our code.

This is how it works. I hope this gives you an idea of how to render an image to a size you want.