herokuでdeviseとcarrierwaveを使ったアプリをつくる
herokuはpublicフォルダに書き込みできないので、ファイルのアップロードが試せない。なので、Base64エンコードしてDB内に文字列として持つようにしてみる。画像ファイル限定で。
以下、作業履歴。
プロジェクト「myphotogallery」を作成
Gemfileに追記
gem 'rake', '0.8.7' gem 'devise' gem 'carrierwave'」
「bundle update」を実行
「rails g devise:install」を実行
Userモデルを作る
「rails g devise user」を実行
Photoモデルを作る
「rails g scaffold photo pict:string pictcode:text user:references」
Userモデルに追記
has_many :photos
PictUploaderを生成
「rails g uploader pict」を実行
Photoモデルに追記
attr_accessible :pict mount_uploader :pict, PictUploader before_save :set_code def set_code self.pictcode = "data:image/#{self.pict.file.extension};base64," self.pictcode << Base64.encode64(self.pict.file.read) end
PictUploaderを修正
16行目の保存先を修正してchacheディレクトリの指定も
def store_dir "#{Rails.root}/tmp/uploads#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end #メソッド追加(これがないとpublicに空ディレクトリを作ろうとしてコケる) def cache_dir "#{Rails.root}/tmp/uploads" # for heroku read-only filesystem end
Viewの修正
app/views/photos/_form.html.erb
1行目 <%= form_for(@photo, :html => {:multipart => true}) do |f| %> 16行目 <%= f.file_field :pict %> 22〜23行目 コメントアウト
app/views/photos/show.html.erb
10行目 <img src="<%= @photo.pictcode %>">
Photosコントローラの修正
2行目に追加 before_filter :authenticate_user!, :except => [:index, :show] 44行目コメントアウト-45行目 @photo = current_user.photos.build(params[:photo]) 61行目コメントアウト-62行目 @photo = current_user.photos.find(params[:id]) 78行目コメントアウト-79行目 @photo = current_user.photos.find(params[:id])
Routeを設定
55行目 root :to => "photos#index"
public/index.htmlを削除
DBマイグレート
「bundle exec rake db:migrate」
サーバ起動
「rails s」
herokuに送る
「
heroku create 任意の名前
git init
git add .
git commit -am "first commit"
git remote add heroku git@heroku.com:任意の名前.git
git push heroku master
heroku rake db:migrate
」
〜〜2011/06/23 Photosモデルでの処理を追加。で、ビューもちょっと簡単に。