Search code examples
ruby-on-railsjsonrubyruby-on-rails-5rails-activestorage

How to return active storage url that points to an attachment (picture) in Rails app?


I am working on an app where users can create and update their profile pictures. The issue I am having is that when a user creates their profile picture from the mobile device, active storage successfully creates an attachment and blob for the image. However, when the user wants to update their profile image, the old attachment is purged but the URL returned from the S3 service points to a blank image AKA a non-existent image (simply a white screen). sample code showing the update action for the profile picture

I am using the url_for helper to generate a URL for the attachment. I am unsure if this is the right helper method to use. The main problem occurs when updating a users profile picture, not when a user is creating their profile picture.


Solution

  • For an image on S3 I use this for my apps. You will need to change the @ variable to match what you are using and then the field you are using, I took a best guess based on your question. It would be easier going forward to always post the code you are using so we can provide better feedback

    <%= @user.profile_picture.service_url %>
    

    You'll notice that this doesn't work locally so if using both during dev is important to use something like this.

    <%= Rails.env == 'production' ? @user.profile_picture.service_url : url_for(@user.profile_picture) if @user.profile_picture.attached? %>
    

    that will give you the path to the image, then use it however you are, for example, if it is a background image

    <div style='background-image:url("<%= Rails.env == 'production' ? @user.profile_picture.service_url : url_for(@user.profile_picture) if @user.profile_picture.attached? %>");'>