Active Storage 개요

Active Storage 정보



파일 업로드 기능을 쉽게 구현할 수 있는 기능(Gem). Rails에 통합되어 있기 때문에, 지정의 커멘드를 실행하는 것으로 간단하게 도입할 수 있다.
Amazon S3, Google Cloud Storage, Microsoft Azure Storage 등의 클라우드 스토리지 서비스에 대한 파일 업로드를 쉽게 할 수 있다. 클라우드 스토리지 외에도 로컬 디스크에 파일을 저장할 수 있습니다.

Active Storage 사용법



1. Active Storage 설치



Active Storage를 어플리케이션 내에서 사용하기 위한 준비로서 다음 명령을 실행한다.

터미널
rails active_storage:install

위 명령을 실행하면 Active Storage와 관련된 마이그레이션이 생성되므로 마이그레이션하고,
  • active_storage_attachments
  • active_storage_blobs

  • 위 테이블이 데이터베이스에 추가되면 성공

    2. Active Record 모델 준비



    파일 업로드 기능을 사용하고 싶은 모델을 준비한다. (여기에서는 tweet 모델로 둡니다)
    이미지에 대한 열을 준비 할 필요가 없다는 점도 Active Storage의 특징 중 하나

    3. 파일 첨부



    3-1) 하나의 첨부 파일의 경우

    Tweet 모델에 하나의 이미지를 첨부하려면 has_one_attached를 사용합니다.

    tweet.rb
    class Tweet < ApplicationRecord
      has_one_attached :image
    end
    

    tweets_controller.rb
    class TweetsController < ApplicationController
    
      (省略)
    
      def create
        @tweet = Tweet.new(tweet_params)
        if @tweet.save
          redirect_to root_path
        else
          render 'new'
        end
      end
    
      (省略)
    
      private
    
      def tweet_params
        params.require(:tweet).permit(:image, :text).merge(user_id: current_user.id)
      end
    
    end
    

    3-1) 여러 첨부 파일의 경우



    Tweet 모델에 하나의 이미지를 첨부하려면 has_many_attached를 사용합니다.
    양식의 file_field에 multiple: true를 추가하여 여러 파일을 선택할 수 있습니다.

    tweet.rb
    class Tweet < ApplicationRecord
      has_many_attached :images
    end
    

    tweets_controller.rb
    class TweetsController < ApplicationController
    
      (省略)
    
      def create
        @tweet = Tweet.new(tweet_params)
        if @tweet.save
          redirect_to root_path
        else
          render 'new'
        end
      end
    
      (省略)
    
      private
    
      def tweet_params
        params.require(:tweet).permit(:images, :text).merge(user_id: current_user.id)
      end
    
    end
    
    

    new.html.erb
    <%= form_with model: @tweet, local: true  do |f| %>
      <%= f.file_field :images, multiple: true %>
      <%= f.text_area :text %>
      <%= f.submit %>
    <% end %>
    

    4. 파일을 저장할 위치



    파일의 저장처는 각 환경의 설정 파일에 기재되어있다.
    초기 상태에서는 개발 환경(development), 프로덕션 환경(production) 모두 저장처는 :local 로 설정되어 있다. 이 local은 config/storage.yml에 정의된 대상 이름입니다. (저장처의 변경에 대해서는 다른 기사로 기재하고 싶습니다 )

    참고



    h tps : // / ls lgus s. jp/あcちゔぇ_s토레게_오오ㅇㅜㅜㅜ HTML
    htps : // m / hm rj / ms / 7c5 5348755c517458

    좋은 웹페이지 즐겨찾기