当前位置: 首页 > 工具软件 > carrierwave > 使用案例 >

rails中使用carrierwave上传图片

葛烨
2023-12-01

1.安装

gem install carrierwave

2.更新 Gemfile

gem 'carrierwave'

3.生成uploader

rails generate uploader Avatar

生成文件:app/uploaders/avatar_uploader.rb

4.挂载属性

文件上传后存储的是图片的路径,存储图片路径的字段挂载AvatarUploader.比如model Book有四个属性name 、author 、publish 、picture_url,在model中加上一行:

class Book < ActiveRecord::Base
    mount_uploader :picture_url, AvatarUploader
end

5.修改app/uploaders/avatar_uploader.rb

# encoding: utf-8

class AvatarUploader < CarrierWave::Uploader::Base

uploader:
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

   def extension_white_list
     %w(jpg jpeg gif png)
   end
end

6.给表单加上图片上传域

    <p>
      <%= f.label :上传图书图片 %><br />
      <%= f.file_field :picture_url %>
      <%= f.hidden_field :picture_url_cache %>
    </p>

7.修改controller

def create
        @book = Book.new(book_params)
        @book.picture_url= params[:file]
        ...
end

8.引用图片路径

<%= image_tag @book.picture_url_url.to_s %>

carrierwave github:carrierwave

 类似资料: