スムーズにうまく行ったのでメモ。
Ralis5
Ubuntu16
GemFileに追加する
gem 'carrierwave'
gem 'mini_magick'
コマンド入力
$ bundle
$ rails g scaffold upload image:string content:text name:string
$ rails g uploader images
$ rails db:migrate
必要事項の追記
Scaffoldで作ったuploadのmodelsに追記
app/models/upload.rb
class Upload < ApplicationRecord
mount_uploader :image, ImagesUploader
end
CarrierWaveのファイルに追加
app/uploaders/images_uploader.rb
class ImagesUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# 許可する画像の拡張子
def extension_whitelist
%w(jpg jpeg gif png)
end
# サムネイル画像
version :thumb do
process resize_to_fill: [80, 80]
end
# Maxサイズ
version :content do
process resize_to_limit: [640, 640]
end
end
Viewsファイルを修正・追加
_horm.html.erb
app/views/uploads/_horm.html.erb
<div class="field">
<%= form.label :image %>
<%= form.file_field :image %>
</div>
show.html.erb
app/views/uploads/show.html.erb
<%= image_tag @upload.image_url(:content) if @upload.image.present? %>
index.html.erb
app/views/uploads/index.html.erb
<table>
<thead>
<tr>
<th>Image</th>
<th>Content</th>
<th>Name</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @uploads.each do |upload| %>
<tr>
<td>
<%= image_tag upload.image_url(:thumb) if upload.image.present? %>
</td>
<td><%= upload.content %></td>
<td><%= upload.name %></td>
<td><%= link_to 'Show', upload %></td>
<td><%= link_to 'Edit', edit_upload_path(upload) %></td>
<td><%= link_to 'Destroy', upload, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
これで画像のサムネイル投稿、最大サイズの制限、投稿拡張子の制限ができる。
##サムネイルには
ImageMagick が必要なのでサーバーに入れてない場合は入れる。
画像にリンクをつける
app/views/uploads/index.html.erb
<%= link_to (image_tag upload.image_url(:thumb) if upload.image.present?), upload %>
または
app/views/uploads/index.html.erb
<%= link_to upload do %>
<%= image_tag upload.image_url(:thumb) if upload.image.present? %>
<% end %>