Skip to content

Instantly share code, notes, and snippets.

@caok
Last active August 29, 2015 14:09
Show Gist options
  • Save caok/515b4552f2029bf83b34 to your computer and use it in GitHub Desktop.
Save caok/515b4552f2029bf83b34 to your computer and use it in GitHub Desktop.
paperclip

gem "paperclip", "~> 4.2"

paperclip

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

必须指定上传文件类型validates_attachment_content_type 否则可以允许任意类型

do_not_validate_attachment_file_type :avatar

Migrations

rails generate paperclip user avatar

class AddAvatarColumnsToUsers < ActiveRecord::Migration
  def self.up
    add_attachment :users, :avatar
  end

  def self.down
    remove_attachment :users, :avatar
  end
end

# 修改字段
def self.up
  remove_column :carousel_features, :thumbnail
  add_attachment :carousel_features, :thumbnail
end
 
def self.down
  remove_attachment :carousel_features, :thumbnail
  add_column :carousel_features, :thumbnail, :string
end

Edit and New Views

<%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :avatar %>
<% end %>

Controller

def create
  @user = User.create( user_params )
end

private
def user_params
  params.require(:user).permit(:avatar)
end

Show View

<%= image_tag @user.avatar.url %>
<%= image_tag @user.avatar.url(:medium) %>
<%= image_tag @user.avatar.url(:thumb) %>

Deleting an Attachment

Set the attribute to nil and save.

@user.avatar = nil
@user.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment