DEV Community

Joshua Shane Doud Jr.
Joshua Shane Doud Jr.

Posted on

Leveraging Active Storage in Ruby on Rails and React

Introduction:

In the dynamic landscape of web development, seamlessly handling file uploads and storage is a crucial aspect of building modern applications. Ruby on Rails, a robust back-end framework, simplifies this process with its Active Storage feature. When paired with the powerful front-end library React, developers can create a smooth and efficient experience for users.

In this comprehensive guide, we'll explore the integration of Active Storage in Ruby on Rails with a React front end. We'll cover everything from setting up Active Storage to handling file uploads and rendering images in a React application.

Getting Started:

Setup Ruby on Rails with Active Storage:
Start by creating a new Rails application or integrating Active Storage into an existing one. Ensure you have the necessary gems installed:

gem 'rails', '~> 6.0'
gem 'image_processing'
Enter fullscreen mode Exit fullscreen mode

Run bundle install to install these gems. Next, set up Active Storage by running:

rails active_storage:install
rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Configure Models:
Incorporate Active Storage into your models by using the has_one_attached or has_many_attached macro. For example, in a Post model:

class Post < ApplicationRecord
  has_one_attached :image
end
Enter fullscreen mode Exit fullscreen mode

Handling File Uploads:

Create a Form in React:
When integrating with React, create a form that allows users to upload files. Utilize the fetch API or a library like Axios to send the file to your Rails backend. Here's a simple example using React and Axios:

import React, { useState } from 'react';
import axios from 'axios';

const FileUploadForm = () => {
  const [file, setFile] = useState(null);

  const handleFileChange = (event) => {
    setFile(event.target.files[0]);
  };

  const handleUpload = async () => {
    const formData = new FormData();
    formData.append('image', file);

    try {
      await axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      console.log('File uploaded successfully!');
    } catch (error) {
      console.error('Error uploading file:', error);
    }
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleUpload}>Upload</button>
    </div>
  );
};


export default FileUploadForm;
Enter fullscreen mode Exit fullscreen mode

Handle File Upload in Rails:
In your Rails controller, handle the file upload by attaching it to the corresponding model. For instance:

class ApiController < ApplicationController
  def upload
    post = Post.create
    post.image.attach(params[:image])
    render json: { status: 'success' }
  end
end
Enter fullscreen mode Exit fullscreen mode

Rendering Images in React:

Retrieve Image URLs:
After a successful upload, you'll want to retrieve the URL of the uploaded image from the Rails backend. Modify the Rails controller to include the image URL in the response.

class ApiController < ApplicationController
  def upload
    post = Post.create
    post.image.attach(params[:image])
    render json: { status: 'success', image_url: url_for(post.image) }
  end
end
Enter fullscreen mode Exit fullscreen mode

Display Images in React:
Update your React component to display the uploaded image using the received URL.

import React, { useState } from 'react';
import axios from 'axios';

const FileUploadForm = () => {
  const [file, setFile] = useState(null);
  const [imageUrl, setImageUrl] = useState(null);

  const handleFileChange = (event) => {
    setFile(event.target.files[0]);
  };

  const handleUpload = async () => {
    const formData = new FormData();
    formData.append('image', file);

    try {
      const response = await axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      setImageUrl(response.data.image_url);
      console.log('File uploaded successfully!');
    } catch (error) {
      console.error('Error uploading file:', error);
    }
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button onClick={handleUpload}>Upload</button>
      {imageUrl && <img src={imageUrl} alt="Uploaded" />}
    </div>
  );
};

export default FileUploadForm;
Enter fullscreen mode Exit fullscreen mode

Conclusion:

In this guide, we've covered the integration of Active Storage in Ruby on Rails with a React front end. From setting up Active Storage to handling file uploads and rendering images in a React application, you now have a solid foundation for managing file storage in your web projects.

By combining the strengths of Ruby on Rails and React, you can create a seamless user experience with efficient file management. As you continue to explore and refine your skills in these technologies, you'll be well-equipped to build robust and user-friendly applications. Happy coding!

Top comments (0)