CodexBloom - Programming Q&A Platform

Rails 7.1: Difficulty with ActiveStorage direct uploads scenarios with custom URL options

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
ruby-on-rails activestorage direct-uploads aws-s3 Ruby

I keep running into I'm working on a project and hit a roadblock... Does anyone know how to I'm upgrading from an older version and I'm stuck on something that should probably be simple. I'm working with an scenario with direct uploads in ActiveStorage when trying to customize the URL options in Rails 7.1. I've set up direct uploads for images, and while the upload works fine, I'm working with an behavior when I try to use a custom host for the upload URL. The behavior message states `ActiveStorage::DirectUploadError (The host is not allowed.)`. Here's the configuration I have in my `storage.yml`: ```yaml local: service: Disk root: <%= Rails.root.join('storage') %> amazon: service: S3 access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %> secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %> region: <%= ENV['AWS_REGION'] %> bucket: <%= ENV['AWS_BUCKET'] %> ``` In my controller, I'm attempting to set a custom URL: ```ruby # app/controllers/uploads_controller.rb class UploadsController < ApplicationController def create @upload = Upload.new(upload_params) if @upload.save render json: @upload, status: :created else render json: @upload.errors, status: :unprocessable_entity end end private def upload_params params.require(:upload).permit(:image) end end ``` And in my JavaScript file, I'm specifying the URL for the direct upload: ```javascript // app/javascript/packs/uploads.js const uploadImage = (file) => { const url = `/uploads`; const formData = new FormData(); formData.append('upload[image]', file); return fetch(url, { method: 'POST', body: formData, headers: { 'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content } }); }; ``` Despite having the correct configuration and ensuring that the host is included in the `allowed_hosts` configuration in my environment file (`config/environments/development.rb`), I'm still getting the behavior. Here’s what I added: ```ruby # config/environments/development.rb Rails.application.configure do # Other configurations... config.active_storage.service_urls_expire_in = 1.hour config.active_storage.allowed_hosts = ['localhost:3000', 'my-custom-host.com'] end ``` I've verified that `my-custom-host.com` is the correct host but still get the behavior. Has anyone faced a similar scenario or can point out what I'm missing in my setup? What am I doing wrong? This is happening in both development and production on Linux. Is this even possible? The project is a REST API built with Ruby. I'd really appreciate any guidance on this.