How to Upload mp3’s to your Rails Backend Using Active Storage

Noah Shafer
2 min readJul 31, 2020

--

Saving mp3’s to in a rails backend seems like it would be a tricky thing to accomplish, but thanks to rails Active Storage it’s relatively simple.

The first time encountered this problem for an app I was building that needed to save mp3’s, I figured I was going to have to convert my mp3 data to a base64 string and then save that string in the database and then use that data to play the mp3 on the front end. After, a little bit of digging I discovered this was not the case. Turns out you can easily store mp3’s in your rails backend using Active Storage.

1. Declare Active Storage Services

In your config/storage.yml file, you can set up your configurations

The test and local configurations should already be set up for you when you generate your rails API, however you can set up other storage services here as well i.e. amazon, google, etc.

2. Tell Active Storage which service to use

Well just be configuring active storage for development, however you can also configure these for testing and production

In your config/environments/development.rb, you can tell active storage to use the local disk to store files

Now that’s it for configuring active storage, now we just need to set up our model so we can attach an mp3 to it.

3. Setup your model to attach an mp3

This part is pretty simple, you just have use the has_one_attached macro to set up a one-to-one relationship between records and files, records can only have one file attached to it.

Just like that now you can store mp3’s in your rails backend. Here is how I associated mp3 files with our models.

If you would like more info on how active storage you can checkout the overview here:

https://edgeguides.rubyonrails.org/active_storage_overview.html

--

--