LoginSignup
0
0

More than 5 years have passed since last update.

rails4 で paperclip を使ってみた。

Posted at

前提条件

  • rails4
  • ruby 2.1
  • imagemagickがインストール済み

まずはプロジェクトの作成

$ rails new papercliptest
$ cd papercliptest

Gemfileにpaperclipを追加する。

Gemfile
...
gem "paperclip", "~> 4.3"

画像登録用のモデルをscaffoldする。

$ rails g scaffold picture name:string
$ rails g paperclip picture photo
$ rake db:migrate

modelの修正

app/model/picture.rb
class Picture < ActiveRecord::Base
  has_attached_file :photo,
                    :styles => { :medium => "300x300>", :thumb => "100x100>" },
                    :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
end

viewsの修正

app/views/pictures/_form.html.erb
...
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <!-- photoの入力フォームを追加 -->
  <div class="field">
    <%= f.file_field :photo %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
...
app/views/pictures/show.html.erb
...
<p>
  <strong>Picture(original):</strong>
  <%= image_tag @picture.photo.url(:original) %>
</p>
<p>
  <strong>Picture(medium):</strong>
  <%= image_tag @picture.photo.url(:medium) %>
</p>
<p>
  <strong>Picture(thumb):</strong>
  <%= image_tag @picture.photo.url(:thumb) %>
</p>
...

controllerの修正

app/controllers/pictures_controller.rb
def picture_params
  params.require(:picture).permit(:name, :photo)
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0