ジェネレータでup用クラス作成
rails g uploader Image
つけた名前のあとにUploaderて名前がついたファイルが出来るっぽい
モデルとアップデートファイルを結びつける
mount_uploader :about_image1, ImageUploder
mount_uploader :about_image2,ImageUploder
S3に入れる場合 initializersにcarrierwave.rbとか作って設定入れる
Uploaderファイルを変更
include CarrierWave::RMagick
#S3に上げるのでfogを使う
storage :fog
#S3保存するディレクトリ場所
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
#キャッシュファイルの置き場所をルートから変えたい時設定
def cache_dir
"uploads_tmp/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
#変換したファイルのファイル規則
def filename
"#{secure_token}.#{file.extension}" if original_filename.present?
end
protected
def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end
上でファイルと結びつけたカラムをマイグレーションで作成、複数の場合はファイル保存用テーブル作成
class NoticeFile < ActiveRecord::Base
belongs_to :hogeration
acts_as_paranoid
mount_uploader :file_path, NoticeUploader
end
viewを準備
hiddenフィールドをつけるとバリでショーンエラーになっても値が消えない。でもモデルに定義されてないとダメっぽ‥
.row
.col-xs-12.col-sm-4
= f.label "添付ファイル"
.col-xs-12.col-sm-8
- (1..3).each do |key|
= f.file_field "about_image#{key}".to_sym, class: 'file-inline'
= f.hidden_field :"about_image#{key}_cache"
後は適当にコントローラで保存すればおk ←書くのがメンドクサクなった