初めに
localのstorage => Railsのアセットパイプライン下に保存 => 読み込み の流れです。
環境: Rails 5.1.4
Gemfile
gem paperclip
terminal
$ bundle install
model Picture
terminal
$ rails g model Picture name:string
$ rails db:migrate
paperclipを使うために必要なカラムを足す。
以下のようにすると、”photo”カラムが追加されるだけでなく、
photo_file_name,photo_file_sizeなどpaperclipに必要なカラムが追加されます。
terminal
$ rails g paperclip picture photo
こんな感じのmigrationファイル
※[5.1]を足さないとエラーになるので注意
class AddAttachmentPhotoToPictures < ActiveRecord::Migration[5.1]
def self.up
change_table :pictures do |t|
t.attachment :photo
end
end
def self.down
remove_attachment :pictures, :photo
end
end
$ rails db:migrate
paperclipの設定
ここでは、保存先のパスをapp/assets/imagesにして、Railsから読み込むようにしています。
ローカル完結型。
models/picture.rb
class Picture < ApplicationRecord
has_attached_file :photo,
styles: { medium: "300x300>", thumb: "100x100>" },
path: "#{Rails.root}/app/assets/images/:filename"
validates_attachment_content_type :photo, content_type: /\Aimage\/.*\z/
end
controller と route
routes.rb
get 'pictures/new'
get 'pictures/index'
post 'pictures' => 'pictures#create'
terminal
rails g controller Pictures
app/controllers/pictures_controller.rb
class PicturesController < ApplicationController
def new
@picture = Picture.new
end
def create
@picture = Picture.new(picture_params)
if @picture.save
redirect_to '/pictures/index'
end
end
def index
@pictures = Picture.all
end
private
def picture_params
params.require(:picture).permit(:photo)
end
end
View
new.html.erb
<%= form_for @picture, url: pictures_path do |f| %>
<%= f.text_field :name %>
<%= f.file_field :photo %>
<%= f.submit %>
<% end %>
index.html.erb
<h1>All Photos</h1>
<ul class="pictures" >
<%= render @pictures %>
</ul>
_picture.html.erb
<li>
<%= picture.photo_file_name %>
<%= image_tag picture.photo_file_name %>
</li>
参照
https://github.com/thoughtbot/paperclip
RailsでPaperclipを使ってファイルをアップロードする