保华的Rails学习笔记

用carriver与mini_magick上传图片

1、安装carrierwave and mini_magick

1)在gem里边添加:
gem 'carrierwave'
gem 'mini_magick'
2)执行 brew install imagemagick
3)bundle install
4)执行 rails g uploader image
5)重开 rails s

2、在product新增image栏位

1)rails g migration add_image_to_product
2)添加栏目

db/migrate/XXX(一堆数字)_add_image_to_product.rb
class AddImageToProduct < ActiveRecord::Migration[5.0]
  def change
    add_column :products, :image, :string
  end
end

3)执行rake db:migrate

3、挂上 image uploader

app/models/product.rb
class Product < ActiveRecord::Base
+ mount_uploader :image, ImageUploader
end

4、设定图片上传后裁切的尺寸

app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:

  # include CarrierWave::RMagick

- # include CarrierWave::MiniMagick

+ include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:

  storage :file
  # storage :fog


  # Override the directory where uploaded files will be stored.

  # This is a sensible default for uploaders that are meant to be mounted:

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

+ process resize_to_fit: [800, 800]

+ version :thumb do
+   process resize_to_fill: [200,200]
+ end

+ version :medium do
+   process resize_to_fill: [400,400]
+ end
...(略)

5、新增商品时可以上传商品照片

app/controllers/admin/products_controller.rb
...(略)
   def new
     @product = Product.new
   end
   
...(略)

   def product_params
-    params.require(:product).permit(:title, :description, :quantity, :price)
+    params.require(:product).permit(:title, :description, :quantity, :price, :image)
   end

...(略)
app/views/admin/products/new.html.erb
...(略)
  <div class="group">
    <%= f.input :price %>
  </div>
  
+ <div class="group">
+   <%= f.input :image, as: :file %>
+ </div>

  <%= f.submit "Submit", data: { disable_with: "Submitting..." } %>
...(略)

6、商品修改页也能修替换图片

app/views/admin/products/edit.html.erb
...(略)
  <div class="group">
    <%= f.input :price %>
  </div>

+ <% if @product.image.present? %>
+   <span>目前商品图</span> <br>
+   <%= image_tag(@product.image.thumb.url) %>
+ <% end %>

+ <div class="group">
+   <%= f.input :image, as: :file %>
+ </div>

  <%= f.submit "Submit", data: { disable_with: "Submitting..." } %>
...(略)

7、将 uploads 资料夹放入 gitignore

.gitigonre
...(略)
config/database.yml
+ public/uploads