Search code examples
rubyruby-on-rails-5rails-activestorage

How to add a default attachment in rails Activestorage


I have a model Post with

has_one_attached :cover

Having an attachment is not necessary. So, is there any way that I can add a default attachment even if the user doesn't provide one.

So, when the post is displayed there is a cover image I can show.

<% if @post.cover.attached? %>
    <%= image_tag(@post.cover, class: 'card-img-top img-fluid') %>
<% else %>
    <div class="text-align-center img-place-holder">
          No Image Added Please add One
   </div>
<% end %>

Is there any way other than checking if something is attached and trying to resolve it like this.

So, I could use,

<%= image_tag(@post.cover, class: 'card-img-top img-fluid') %>

directly without any if condition

thank you


Solution

  • If you want to attach a default image to post if one is not present then you can do this in a callback

    # 1. Save a default image in Rails.root.join("app", "assets", "images", "default.jpeg")
    
    # 2. In post.rb
    
    after_commit :add_default_cover, on: [:create, :update]
    
    
    private def add_default_cover
      unless cover.attached?
        self.cover.attach(io: File.open(Rails.root.join("app", "assets", "images", "default.jpeg")), filename: 'default.jpg' , content_type: "image/jpg")
      end
    end
    
    # 3. And in your view 
    <%= image_tag(@post.cover, class: 'card-img-top img-fluid') %>
    

    Or, If you don't want to attach the default cover to post but still want to show a image on post's show page

    # 1. Save a default image in Rails.root.join("app", "assets", "images", "default.jpeg")
    
    # 2. In post.rb
    
    def cover_attachment_path
      cover.attached? ? cover : 'default.jpeg'
    end
    
    # 3. And in your view
    <%= image_tag(@post.cover_attachment_path, class: 'card-img-top img-fluid') %>