All Articles

Rails Generator Handles Active Storage Attachment Fields

Rails Active Storage allows attaching one or many attachment to the Active Record object and uploading the attachables to the cloud storage services like AWS, GCP.

To configure Active Record model to associate attachment, you need to configure has_one_attached as follows in the model.

class User < ApplicationRecord
  has_one_attached :user

Today I learned, you can configure Active Storage attachment fields using Rails model and scaffold generator by providing attachment or attachments field attribute field attribute. The model and scaffold generator would configure Active Record model with the appropriate Active Storage configuration.

Run the model generator as follows to configure has_one_attached for avatar in the user model.

$ bin/rails generate model <ModelName> <association_name>:<association_type>

<association_type> can be attachment or attachments. Added documentation for same in the Rails guides: PR#42391

attachment: has_one_attached
attachments: has_many_attached

Has One Attached Using Attachment

Similar to model generator, scaffold generator takes one step further with configuring the views with file_field for attachment.

Has Many Attached Using Attachment

Happy Coding!!