Rails + Paperclipを試す

プロジェクトを新規作成

$rails new paperclipdemo -d mysql
$cd paperclipdemo
$bundle install --path vendor/bundler
$rails s -p80

scaffoldを作成

$rails g scaffold events name:string
$rake db:create
$rake db:migrate

Gemをupdate(PaperclipとAWS-SDKを追加する)

#vim Gemfile
----------------------
gem 'paperclip'
gem 'aws-sdk'
----------------------
$bundle install --path vendor/bundler

columnをupdateする(paperclipのコマンドを利用する)

$rails g paperclip event image
$rake db:migrate

Modelを修正する

# vim app/model/event.rb
class Event < ActiveRecord::Base
  has_attached_file :image,
    :storage => :s3,
    :s3_credentials => "#{Rails.root}/config/s3.yml",
    :path => ":attachment/:id/:style.:extension"
end

s3.ymlを作成する

# vim config/s3.yml
bucket: hogehoge
access_key_id: abcd
secret_access_key: abcd
s3_host_name: s3-ap-northeast-1.amazonaws.com

Controllerのパラメーターを修正(imageを追記)

# (これを通さないとUnpermitted parameters: imageで怒られる)
def event_params
  params.require(:event).permit(:name,:image)
end

Formテンプレートを修正

#vim app/view/events/_form.html.erb
<%= form_for(@event, :html => { :multipart => true }) do |f| %>
  <div class="field">
    <%= image_tag @event.image.url if @event.image.present? %>  
    <%= f.label :image %><br />
    <%= f.file_field :image %>
  </div>
<% end %>

Showテンプレートを修正

#vim app/view/events/show.html.erb
  <b>Image:</b>
  <%= image_tag @event.image.url if @event.image.present? %>