0
0
Ruby on Railsframework~5 mins

Image and file handling in Ruby on Rails

Choose your learning style9 modes available
Introduction

We use image and file handling to let users upload and show pictures or files in a web app. It helps store and display these files easily.

When users need to upload profile pictures.
When you want to attach documents to a form.
When showing product images in an online store.
When saving and displaying user-submitted files like PDFs or images.
Syntax
Ruby on Rails
has_one_attached :image
has_many_attached :files

Use has_one_attached for a single file like a profile photo.

Use has_many_attached for multiple files like photo albums.

Examples
This lets each user have one avatar image attached.
Ruby on Rails
class User < ApplicationRecord
  has_one_attached :avatar
end
This allows a post to have many images attached.
Ruby on Rails
class Post < ApplicationRecord
  has_many_attached :images
end
Sample Program

This example shows how to set up a Product model with one photo. The controller attaches the uploaded file. The view shows the photo if it exists.

Ruby on Rails
class Product < ApplicationRecord
  has_one_attached :photo
end

# In a controller, to attach an uploaded file:
# @product.photo.attach(params[:photo])

# In a view (ERB) to show the image:
# <% if @product.photo.attached? %>
#   <%= image_tag @product.photo %>
# <% else %>
#   <p>No photo available</p>
# <% end %>
OutputSuccess
Important Notes

Rails uses Active Storage to handle files easily.

Files are stored on disk or cloud services like Amazon S3.

Always check if a file is attached before showing it to avoid errors.

Summary

Use has_one_attached or has_many_attached to link files to models.

Attach files in controllers and display them in views.

Check if files exist before showing them to users.