You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Then add config/initializers/shrine.rb which sets up the storage and loads
ORM integration:
require"shrine"require"shrine/storage/file_system"Shrine.storages={cache: Shrine::Storage::FileSystem.new("public",prefix: "uploads/cache"),# temporarystore: Shrine::Storage::FileSystem.new("public",prefix: "uploads"),# permanent}Shrine.plugin:activerecord# loads Active Record integrationShrine.plugin:cached_attachment_data# enables retaining cached file across form redisplaysShrine.plugin:restore_cached_data# extracts metadata for assigned cached files
Next, add the <name>_data column to the table you want to attach files to. For
an "image" attachment on a photos table this would be an image_data column:
$ rails generate migration add_image_data_to_photos image_data:text # or :jsonb
If using jsonb consider adding a gin index for fast key-value pair searchability within image_data.
Now create an uploader class (which you can put in app/uploaders) and
register the attachment on your model:
classImageUploader < Shrine# plugins and uploading logicend
classPhoto < ActiveRecord::BaseincludeImageUploader::Attachment(:image)# adds an `image` virtual attributeend
In our views let's now add form fields for our attachment attribute that will
allow users to upload files:
<%= form_for @photo do |f| %><%= f.hidden_field :image, value: @photo.cached_image_data, id: nil %><%= f.file_field :image %><%= f.submit %><% end %>
When the form is submitted, in your controller you can assign the file from
request params to the attachment attribute on the model:
classPhotosController < ApplicationControllerdefcreatePhoto.create(photo_params)# attaches the uploaded file# ...endprivatedefphoto_paramsparams.require(:photo).permit(:image)endend
Once a file is uploaded and attached to the record, you can retrieve the file
URL and display it on the page:
Shrine was heavily inspired by Refile and Roda. From Refile it borrows the
idea of "backends" (here named "storages"), attachment interface, and direct
uploads. From Roda it borrows the implementation of an extensible plugin
system.