How to add a default attachment in rails Activestorage
Asked Answered
I

1

7

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

Iva answered 12/6, 2018 at 7:40 Comment(0)
P
14

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') %>
Polacre answered 15/6, 2018 at 8:9 Comment(1)
This will error if you serve images with webpacker as the default value will need to be served with an image_pack_tag rather than an image_tagIdolah

© 2022 - 2024 — McMap. All rights reserved.