Rails ActiveStorage

Rails ActiveStorage

enmanuelm19@gmail.com2018-06-26 14:21:09 UTC

Rails ActiveStorage


ActiveStorage is the native solution of the Rails framework to handle file storage that is present since version 5.2, before this version we usually use gems like Paperclip or Carrierwave, now it's integrated by default.

To start to make use of this new feature we need to put the following command from our application:

railg g active_storage:install

This command will create the necesary migrations in order to persist the information about our attachments. To add an attachment to our models we have to write the following:

class Post < ApplicationRecord
  # If we need only one attachment
  has_one_attached :image

    # If we need multiple attachments
  has_many_attached :images
end

After setting our attachments to their respective models, we need to add the new attribute to the strong params filter in the controller and do the respective changes in the forms: ruby class PostsController < ApplicationController ... def post_params params.require(:post).permit(:name, :image, images: []) end end

# slim
=  form_for @post do |f|
  = f.file_field :image
    = f.file_field :images, multiple: true

# erb
<%= form_for @post do |f| %>
  <%=  f.file_field :image %>
    <%= f.file_field :images, multiple: true %>
<%= end %>

In order to extract the images and show them inside the applications we just need to write the following(assuming that our attachment is an image file):

#slim
- if @post.image.attached?
  = image_tag(@post.image)

#erb
<% if @post.image.attached %>
  <%= image_tag(@post.image) %>
<% end %>

# To handle multiple attachments we just need to iterate over them
- @post.images.each do |image|

# To show the image in a new tab
= link_to image_tag(@post.image), @post.image, target: '_blank'

<%= link_to image_tag(@post.image), @post.image, target: '_blank' %>

# To download the attachments instead of showing them
= link_to @post.image.filename, rails_blob_path(@post.image, disposition: :attachment)

<%= link_to @post.image.filename, rails_blob_path(@post.image, disposition: :attachment)
ActiveStorage and Amazon S3

S3 es un servicio de almacenamiento de archivos que presta Amazon, en esta sección veremos como integrar ActiveStorage para almacenar nuestras imágenes, documentos o archivos adjuntos en el servicio de Amazon.

  1. Crear cuenta en Amazon Primero que todo necesitas crearte una cuenta en Amazon Web Services y seguir los pasos que allí te indican.

  2. Crear bucket de S3 Para crear un bucket ubicamos en el menú de servicios el servicio de S3, y luego hacemos clic en el botón Crear bucket Crear bucket

    Luego de crear nuestro bucket, para no tener problemas con acceder desde nuestra aplicación a los archivos configuramos los CORS CORS

  3. Configurar la aplicación.

    Añadimos la gema aws-sdk-s3 a nuestro Gemfile:

    gem 'aws-sdk-s3', required: false
    

    Dentro de el archivo config/storage.yml colocamos lo siguiente:

    amazon:
        service: S3
        access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
        secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
        region: us-la_region_que_configuraste
        bucket: nombre-bucket
    

    Como pueden observar hacemos uso de las credenciales de Rails, para sabes como utilizarlas puedes revisar Rails credentials.

    Asegurarnos de tener incluido el Javascript necesario para ActiveStorage en app/assets/javascripts/application.js

    //= require activestorage
    

    Indicarle a nuestra aplicación que servicio va a usar para almacenar nuestros archivos, si lo quieres probar en desarrollo se coloca en config/environments/development.rb y por supuesto en config/enviroments/production.rb

    config.active_storage.service = :amazon
    

Y listo ya habremos integrado ActiveStorge con Amazon S3


Cualquier consejo, corrección o duda puedes comentar abajo.


Share