2013年4月21日日曜日

Paperclipライブラリ


railsの画像Upload用ライブラリをつかってみる。
  • paperclip インストール
gemファイルに追記

#Rails file upload library
gem "paperclip", "~> 3.0"

その後

bundle install

  • ImageMagick インストール
aptitude install imagemagick

で、imagemagickのpathをpaperclipに覚えさせる。
今は開発用環境なので、

config/development/environment.rb

で、最後に

Paperclip.options[:command_path] = "ImageMagickのインストールPath"

としてやる

  • Model修正
class Photo < ActiveRecord::Base
  attr_accessible :received, :shooting, :title
  attr_accessible :picture
  has_attached_file :picture, :styles => { :medium => "300x300>", :thumb => "100x100>"} 
end

  • マイグレーションファイル修正 (db/migrate/初回migration日時_create_photos.rb)
class Photo < ActiveRecord::Base
class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.datetime :shooting
      t.datetime :received
      t.string :title
      t.attachment :picture   #Add

      t.timestamps
    end
  end
end

bundle exec rake db:migrate

で、あたらしく項目を追加してあげる。

また、

rails generate paperclip Model名 (ファイルattachする)フィールド名

で、1テーブルへのファイルattouch/detouchができるようにする。


  • Viewの変更
デフォルトFormに追加
  
<%= f.label :picture %>
<%= f.file_field :picture %>

エントリの方

<%= image_tag @photo.picture.url(:thumb) %>




0 件のコメント:

コメントを投稿