導入
前提として、画像保存用のカラムを用意してあること
カラムの型はString
またはtext
gem 'carrierwave'
gem 'rmagick'
rmagick
でエラーが出たら
terminal.app
brew install imagemagick
次にuploaderを作成する
terminal.app
rails g uploader Image #Imageのところは任意の名前,大文字で
先ほどのImageというように命名したとおりのuploader,ここでは,image_uploader.rbというようなuploaderが作られてるはず
次に画像のリサイズなどを記述する
image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
process convert: 'jpg'
# 保存するディレクトリ名
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# thumb バージョン(width 400px x height 200px)
version :thumb do
process :resize_to_fit => [400, 200]
end
# 許可する画像の拡張子
def extension_white_list
%w(jpg jpeg gif png)
end
# 変換したファイルのファイル名の規則
def filename
"#{Time.now.strftime('%Y%m%d%H%M%S')}.jpg" if original_filename.present?
end
end
画像保存用のカラムと関連付けする
任意のモデル.rb
mount_uploader :image, ImageUploader#ここではImageuploader
form_forだと:multipart => true が必要ないそう
form.html.erb
<%= form_tag words_path, method: :create,:multipart => true do %>
<%= fields_for "words[]", @words ,index:nil do |f| %>
<%= f.label :image,"ホーム画像" %>
<%= f.file_field :image,class: 'form_control'%>
<%= submit_tag '完了',class: "btn btn-primary" %>
<%end%>
<% end %>
表示する
show.html.erb
<%= image_tag @word.image_url(:thumb).to_s %>
注意
link_to image_tagで画像にリンクをつけたい時にimage_tag()
にしないといけない、それだけでなく(画像の処理の間にスペースを入れてもいけない
index.html.erb
<%= link_to image_tag(word.image_url(:thumb).to_s),word %>
最後に
form_tagを使って書く方法が圧倒的にform_forを使う情報に比べ少ないので書いた
質問あればよろしくお願いします。