跳到主要內容

發表文章

目前顯示的是有「paperclip」標籤的文章

How to attach a file/image in your data? Using paperclip in a rails application.

在 rails 裡有一個很好用的夾檔套件paperclip,今天就要來簡單介紹paperclip怎麼用. 首先要利用imagemagick套件,讓你的rails專案具有處理影像的能力. Mac OS X $ brew install imagemagick  Linux distribution $ sudo apt-get install imagemagick -y 然後在Gemfile中引用paperclip. # Gemfile ... gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git" ... 記得bundle一下. $ bundle install 接下來利用scaffold製作一個範例,在這個範例中我們要用paperclip幫這個使用者加上照片,paperclip會將照片資料記錄起來並將照片上傳到public資料夾內. $ rails generate scaffold User name:string email:string tel:string  生成附檔資料表 $ rails generate paperclip user avatar 修改 class AddAvatarToUsers < ActiveRecord::Migration[5.2]   def up    add_attachment :users, :avatar   end   def down    remove_attachment :users, :avatar   end end 讓user model知道怎麼處理夾檔,可以上傳的檔案格式容量限制等都可以寫在這裡. # app/models/user.rb  class User < ActiveRecord::Base  has_attached_file :avatar, styles: { medium: "300x300", thumb: "100x100" }   v...