Rails 7.1 returns the Active Storage attachment(s) after saving the attachment

Ghouse Mohamed

By Ghouse Mohamed

on July 26, 2022

This blog is part of our  Rails 7 series.

Previously, saving an attachment to a record returned a boolean, indicating whether or not the attachment was saved to the record. This is not helpful since we have to dig into the record again to retrieve the attachment. Starting Rails 7.1, saving an attachment to a record returns the saved attachment. We can now conveniently use blob methods like #download, #url, #variant etc on the attachment without having to dig into the record again.

Before

1# rails console
2>> @user = User.create!(name: "Josh")
3>> @user.avatar.attach(params[:avatar])
4=> true

After

1# rails console
2>> @user = User.create!(name: "Josh")
3>> @user.avatar.attach(params[:avatar])
4=> #<ActiveStorage::Attached::One:0x00007f075e592380 @name="avatar" @record=#<User:0x00007f075e5924e8 id: "1", name: "Josh">

Please check out this pull request for more details.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.