Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 944
Nijeesh K J Avatar asked Jun 12 '18 07:06

Nijeesh K J


People also ask

How active storage works in Rails?

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.

Where are active storage images stored?

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!

What is Activestorage?

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.


1 Answers

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') %>
like image 57
Nimish Gupta Avatar answered Oct 14 '22 07:10

Nimish Gupta