본문 바로가기

Archived(Programming)/Ruby on Rails(기초)

RubyOnRails 6) Carrierwave 이미지 첨부 기능

RubyOnRails 6) Carrierwave 이미지 첨부 기능


참조 : 

http://flearning-blog.tistory.com/97

https://hcn1519.github.io/articles/2016-02/carrierwave



Carrierwave 젬을 통해 Rails 에서는 이미지를 주고 받을 수 있다.
먼저 gem을 설치한다.

carrierwave 젬이 우리가 원하는 이미지 첨부 기능을 할 메인 젬이고
mini magic은 이미지 크기 조정, fog_aws는 이미지 저장소를 위한 젬이다.

1
2
3
gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'
gem 'mini_magick'
gem 'fog-aws'
cs

그 다음, 터미널에서 다음의 명령어를 수행하여 설치한다.


1
2
3
$ bundle install
$ sudo apt-get update
$ sudo apt-get install imagemagick
cs


그 다음 업로더를 만들어준다.


1
$ rails generate uploader Image
cs


해당, Image_uploader.rb 파일에 가서 몇가지를 수정해줘야 한다.


1
2
3
4
5
6
7
8
9
/app/uploaders/image_uploader.rb
 
1) storage :fog 설정하기!
2) min_magcik 설정하기!
3) extension_whitelist로 원하는 확장자만 업로드 되도록!
4) 파일이름을 랜덤하게 저장할 수 있도록!(겹치지 않게)
def filename
  Time.now.to_i.to_s + ('A'..'Z').to_a.sample(6).join + "." + file.extension if original_filename
end
cs


그리고 아마존 aws에 들어가서 암호와 키를 생성해서 받은 뒤 다음의 명령어들을 처리해준다.

저기 ? 부분에 주어진 id와 key를 입력하면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/config/initialize/fog.rb
 
CarrierWave.configure do |config|
  config.fog_provider = 'fog/aws'                        # required
  config.fog_credentials = {
    provider:              'AWS',                        # required
    aws_access_key_id:     '?',                        # required
    aws_secret_access_key: '?',                        # required
    region:                'ap-northeast-2',             # optional, defaults to 'us-east-1'
    endpoint:              'https://s3.ap-northeast-2.amazonaws.com' # optional, defaults to nil
  }
  config.fog_directory  = 'woongsin94'                                      # required
  config.fog_attributes = {} # optional, defaults to {}
end
cs


그리고 Post 모델 Column에 해당 이미지를 추가해준다. 

여기서 String으로 이미지의 경로를 저장하고 있다가 이를 불러와서 보여주는 방식으로 이미지 저장을 처리한다.

즉, 이미지 자체를 Column으로 가지고 있는 것이 아니라 경로 String을 Column으로 가지는 방식으로 처리한다.

 

1
$ rails g migration AddImageToPosts image:string
$ rails db:migrate
cs


그리고 해당 Post 모델로 가서 다음의 명령어를 추가.


1
2
3
4
5
6
/app/models/post.rb
 
class Post < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end
 
cs


그리고 View 파일들을 수정해준다.


1
2
3
4
5
6
7
8
view 파일들에서 해당 처리
 
enctype="multipart/form-data" 를 form 태그에 추가하기!(new, edit)
보여주기는 다음의 코드를 통햬(show)
<unless @post.image.nil? %>
        
    <%= image_tag @post.image, width: "600" %>
<end %>
cs


마지막으로, Post Controller에 가서 image를 올리는 과정을 처리해준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/app/controllers/posts_controller.rb
 
def create 
    uploader = ImageUploader.new
    uploader.store!(params[:image])
    ~~~
    @post.image = uploader.url
    ~~~
end
 
 
def update
    uploader = ImageUploader.new
    uploader.store!(params[:image])
    ~~~
    @post.image = uploader.url
    ~~~
end
cs