ActiveShrine integrates Shrine file attachments with Active Record models using a familiar API inspired by Active Storage. It provides a simple, flexible way to manage file uploads in your Rails applications while leveraging Shrine's powerful features.
- Active Storage-like API: Familiar
has_one_attached
andhas_many_attached
interface - Customizable Uploaders: Use custom Shrine uploaders with validation, processing, and more
- Polymorphic Associations: Attachments are stored using polymorphic associations
- Eager Loading Support: Prevent N+1 queries with
with_attached_*
scopes
Add ActiveShrine to your application's Gemfile:
gem "active_shrine"
Then execute:
$ bundle install
Generate and run the migration:
$ rails generate active_shrine:install
$ rails db:migrate
Include ActiveShrine::Model
in your models and declare attachments:
class User < ApplicationRecord
include ActiveShrine::Model
has_one_attached :avatar
has_many_attached :photos
end
Work with attachments using a familiar API:
# Attach a file
user.avatar = File.open("avatar.jpg")
user.save
# Access the attachment
user.avatar.url
user.avatar.content_type
user.avatar.filename
# Remove the attachment
user.avatar = nil
user.save
Prevent N+1 queries by eager loading attachments:
# Single attachment
User.with_attached_avatar
# Multiple attachments
User.with_attached_photos
Define custom uploaders with Shrine features and validations:
class ImageUploader < Shrine
plugin :validation_helpers
plugin :derivatives
Attacher.validate do
validate_max_size 10 * 1024 * 1024
validate_mime_type %w[image/jpeg image/png image/webp]
end
Attacher.derivatives do |original|
{
small: shrine_derivative(:resize_to_limit, 300, 300),
medium: shrine_derivative(:resize_to_limit, 500, 500)
}
end
end
Use custom uploaders in your models:
class User < ApplicationRecord
include ActiveShrine::Model
has_one_attached :avatar, uploader: ::ImageUploader
end
After checking out the repo:
- Run
bin/setup
to install dependencies - Run
bundle exec rake test
to run the tests - Run
bin/console
for an interactive prompt
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request
Bug reports and pull requests are welcome on GitHub at https://github.com/radioactive-labs/active_shrine.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the ActiveShrine project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.