Carrierwave on Rails 5.1上传器实例

时间:2018-04-26 13:24:02

标签: ruby-on-rails ruby carrierwave

我遵循了载波指令,我做了rails generate uploader Attachment但我做了

uploader = AttachmentUploader.new
uploader.store!(my_file)

它没有上传my_file附件。我不想将my_file字符串存储在数据库中

1 个答案:

答案 0 :(得分:0)

如果我们看一下CarrierWave的文档

https://github.com/carrierwaveuploader/carrierwave/blob/master/README.md#multiple-file-uploads

我将使用Product作为我想要添加图片的模型,作为示例。  获取主分支Carrierwave并将其添加到您的Gemfile:

| ID | CODE1 | CODE2 |  CODE3 |  CODE4 |  CODE5 |  CODE6 |
|----|-------|-------|--------|--------|--------|--------|
|  1 |   abc |   xyz |    def |    pqr |    jkl |    tuv |
|  2 |   lmn |   rgb | (null) | (null) | (null) | (null) |

在目标模型中创建一个列来托管图像数组:

  gem 'carrierwave', github:'carrierwaveuploader/carrierwave'

运行迁移

rails generate migration AddPicturesToProducts pictures:json

将图片添加到型号产品

bundle exec rake db:migrate

将图片添加到ProductsController中的强参数

app/models/product.rb

class Product < ActiveRecord::Base
  validates :name, presence: true
  mount_uploaders :pictures, PictureUploader
end

允许您的表单接受多张图片

app/controllers/products_controller.rb

def product_params
  params.require(:product).permit(:name, pictures: [])
end

在您的视图中,您可以引用解析图片数组的图像:

app/views/products/new.html.erb

# notice 'html: { multipart: true }'
<%= form_for @product, html: { multipart: true } do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  # notice 'multiple: true'
  <%= f.label :pictures %>
  <%= f.file_field :pictures, multiple: true, accept: "image/jpeg, image/jpg, image/gif, image/png" %>

  <%= f.submit "Submit" %>
<% end %>