2011年5月21日土曜日

Rails File Uploadsライブラリ paperclip


paperclipの使い方で戸惑ったのでメモとして残しておく

たいてはドキュメントに従えば出来ますが、素人衆には若干補足が必要なところがあります(正式ドキュメントhttp://rubydoc.info/gems/paperclip/2.3.11/frames)
インストール
1:ImageMagicをインストール(それぞれの環境のパッケージ管理ソフトでインストールが一番いいと思います)
2.Gemfileの一番下に以下を追加。(railsプロジェクトを作るとプロジェクトの直下にGemfileが作られます)
gem "paperclip", "~> 2.3"
3.$bundle install

既にあるモデルに追加
1.必要なDB項目を追加以下はItemモデルに追加した例
$ rails generate migration add_photo_to_items photo_file_name:string photo_content_type:string photo_file_size:integer  photo_updated_at:datetime
2.モデルの設定を追加 以下はItemモデルに設定を追加した例
class Item < ActiveRecord::Base

    has_attached_file :photo,
     :styles => {
       :thumb=> "100x100>",
       :small  => "400x400>" }
end


3.2をDBに反映
$rake db:migrate

4.画像の追加画面の修正(rails3 の scaffoldで作っている場合はviewの中の_form.html.erbの修正  :html => { :multipart => true }が無いとファイルのアップロードが出来ません)
<%= form_for @item  , :html => { :multipart => true } do |f| %>
  ....
  <%= f.file_field :photo %>
  ....


5.画像の表示画面での修正(show.html.erb   以下は三種類の画像を表示しています)
<% if @item.photo.exists? then %>
<%= image_tag @item. photo.url %>
<%= image_tag @item. photo.url(: thumb) %>
<%= image_tag @item. photo.url(:small) %>
<% end %>


最初からモデルにpaperclip情報を追加する場合
1.itemモデルに追加する場合
$rails generate scaffold item .....photo_file_name:string photo_content_type:string photo_file_size:integer  photo_updated_at:datetime
2.これ以降は”既にあるモデルに追加”の2以降と同じです

入力画面と表示画面は次のようになります


0 件のコメント:

コメントを投稿