0
0
Ruby on Railsframework~30 mins

Image and file handling in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Image and File Handling in Rails
📖 Scenario: You are building a simple Rails app where users can upload profile pictures. The app will store these images and display them on the user's profile page.
🎯 Goal: Learn how to set up image uploading and display using Rails built-in Active Storage. You will create a User model with an attached profile image, configure Active Storage, and display the uploaded image on a profile page.
📋 What You'll Learn
Create a User model with Active Storage attachment
Configure Active Storage in the Rails app
Write code to attach an image file to a user
Display the uploaded image on the user's profile page
💡 Why This Matters
🌍 Real World
Many web apps let users upload profile pictures, product images, or documents. Handling files and images is a common feature.
💼 Career
Understanding Active Storage is essential for Rails developers to manage user uploads securely and efficiently.
Progress0 / 4 steps
1
Set up User model with Active Storage attachment
Create a Rails model called User with a string attribute name. Then add an Active Storage attachment called profile_image to the User model using has_one_attached :profile_image.
Ruby on Rails
Need a hint?

Use rails generate model User name:string to create the model, then add has_one_attached :profile_image inside the model file.

2
Configure Active Storage in the Rails app
Run the Rails command to install Active Storage and generate its tables. Then run the migrations to update the database.
Ruby on Rails
Need a hint?

Use the terminal commands rails active_storage:install and rails db:migrate to set up Active Storage tables.

3
Attach an image file to a user
Write Ruby code to find a User by id 1 and attach an image file located at Rails.root.join('app/assets/images/sample.jpg') to the user's profile_image attachment using attach method.
Ruby on Rails
Need a hint?

Use User.find(1) to get the user and attach(io: File.open(...), filename: 'sample.jpg') to attach the image.

4
Display the uploaded image on the user's profile page
In the Rails view file, write code to display the profile_image of a User object called @user using the image_tag helper and url_for to generate the image URL.
Ruby on Rails
Need a hint?

Check if the image is attached with @user.profile_image.attached? before displaying it with image_tag url_for(...).