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
Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.
By default in the development environment, Active Storage stores all uploaded images on your local disk in the storage subdirectory of the Rails application directory. That's the file you uploaded!
1 What is Active Storage? Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.
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') %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With