&tag(CarrierWave);
gem 'carrierwave' gem 'rmagick'
$ bundle exec rails g uploader image
$ bundle exec rails g migration add_image_to_books image:string #=> db/migrate/xxxxx_add_image_to_users.rbが生成される。
$ bundle exec rake db:migrate
class Book < ApplicationRecord validates :title, :presence => true # 下記を追加 mount_uploader :image, ImageUploader end
def book_params
params.require(:book).permit(:title, :author, :summary, :image)
end
<%= form_with(model: book) do |form| %>
(中略)
<div class="field">
<%= form.label :image %>
<%= form.file_field :image %>
</div>
(中略)
<% end %>
<% if @book.image? %>
<%= image_tag @book.image.url %>
<% else %>
画像がありません
<% end %>
gem 'carrierwave' gem 'rmagick'
$ bundle exec rails g uploader image
$ bundle exec rails g migration add_image_to_books image:string #=> db/migrate/xxxxx_add_image_to_users.rbが生成される。
$ bundle exec rake db:migrate
class Book < ActiveRecord::Base validates :title, :presence => true # 下記を追加 mount_uploader :image, ImageUploader end
def book_params
params.require(:book).permit(:title, :author, :summary, :image)
end
<%= form_for(@book) do |f| %>
(...省略...)
<%= f.label :image %>
<%= f.file_field :image %>
(...省略...)
<% end %>
<% if @book.image? %>
<%= image_tag @book.image.s.url %>
<% else %>
画像がありません
<% end %>
class Book < ActiveRecord::Base validates :title, :presence => true # 下記を追加 mount_uploader :image, ImageUploader mount_uploader :image2, ImageUploader end
def filename
# "image1.jpg" or "image2.jpg"
"#{mounted_as}.jpg"
end
module CarrierWave
module RMagick
def quality(percentage)
manipulate! do |img|
img.write(current_path){ self.quality = percentage } unless img.quality == percentage
img = yield(img) if block_given?
img
end
end
# reduce image noise and reduce detail levels
#
# process :blur => [0, 8]
#
def blur(radius, sigma)
manipulate! do |img|
img = img.blur_image(radius, sigma)
img = yield(img) if block_given?
img
end
end
def unsharp_mask(radius, sigma, amount, threshold)
manipulate! do |img|
img = img.unsharp_mask(radius, sigma, amount, threshold)
img = yield(img) if block_given?
img
end
end
end
end
class ImageUploader < CarrierWave::Uploader::Base
version :m do
process :resize_to_limit => [560, 560]
process :quality => 90
process :unsharp_mask => [2, 1.4, 0.5, 0]
end
end