Rails 4使用carrierwave进行多个图像或文件上传

SSR*_*SSR 86 carrierwave ruby-on-rails-4

如何使用Rails 4和CarrierWave从文件选择窗口上传多个图像?我有一个post_controllerpost_attachments模型.我怎样才能做到这一点?

有人能提供一个例子吗?有一个简单的方法吗?

SSR*_*SSR 194

这是从头开始在rails 4中使用carrierwave上传多个图像的解决方案

或者你可以找到工作演示: 多个附件导轨4

要执行这些步骤.

rails new multiple_image_upload_carrierwave
Run Code Online (Sandbox Code Playgroud)

在宝石文件中

gem 'carrierwave'
bundle install
rails generate uploader Avatar 
Run Code Online (Sandbox Code Playgroud)

创建帖子脚手架

rails generate scaffold post title:string
Run Code Online (Sandbox Code Playgroud)

创建post_attachment脚手架

rails generate scaffold post_attachment post_id:integer avatar:string

rake db:migrate
Run Code Online (Sandbox Code Playgroud)

在post.rb

class Post < ActiveRecord::Base
   has_many :post_attachments
   accepts_nested_attributes_for :post_attachments
end
Run Code Online (Sandbox Code Playgroud)

在post_attachment.rb中

class PostAttachment < ActiveRecord::Base
   mount_uploader :avatar, AvatarUploader
   belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)

在post_controller.rb中

def show
   @post_attachments = @post.post_attachments.all
end

def new
   @post = Post.new
   @post_attachment = @post.post_attachments.build
end

def create
   @post = Post.new(post_params)

   respond_to do |format|
     if @post.save
       params[:post_attachments]['avatar'].each do |a|
          @post_attachment = @post.post_attachments.create!(:avatar => a)
       end
       format.html { redirect_to @post, notice: 'Post was successfully created.' }
     else
       format.html { render action: 'new' }
     end
   end
 end

 private
   def post_params
      params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
   end
Run Code Online (Sandbox Code Playgroud)

在views/posts/_form.html.erb中

<%= form_for(@post, :html => { :multipart => true }) do |f| %>
   <div class="field">
     <%= f.label :title %><br>
     <%= f.text_field :title %>
   </div>

   <%= f.fields_for :post_attachments do |p| %>
     <div class="field">
       <%= p.label :avatar %><br>
       <%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
     </div>
   <% end %>

   <div class="actions">
     <%= f.submit %>
   </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

编辑任何帖子的附件和附件列表. 在views/posts/show.html.erb中

<p id="notice"><%= notice %></p>

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<% @post_attachments.each do |p| %>
  <%= image_tag p.avatar_url %>
  <%= link_to "Edit Attachment", edit_post_attachment_path(p) %>
<% end %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
Run Code Online (Sandbox Code Playgroud)

更新表单以编辑附件views/post_attachments/_form.html.erb

<%= image_tag @post_attachment.avatar %>
<%= form_for(@post_attachment) do |f| %>
  <div class="field">
    <%= f.label :avatar %><br>
    <%= f.file_field :avatar %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

修改post_attachment_controller.rb中的更新方法

def update
  respond_to do |format|
    if @post_attachment.update(post_attachment_params)
      format.html { redirect_to @post_attachment.post, notice: 'Post attachment was successfully updated.' }
    end 
  end
end
Run Code Online (Sandbox Code Playgroud)

在rails 3中,无需定义强参数,因为您可以在模型和accept_nested_attribute中定义attribute_accessible以发布模型,因为在rails 4中不推荐使用可访问属性.

要编辑附件,我们无法一次修改所有附件.所以我们将逐个替换附件,或者您可以根据您的规则进行修改,这里我只是告诉您如何更新任何附件.

  • @SSR - 您的回答非常有帮助.您能否通过编辑操作更新您的答案. (5认同)
  • 很想看编辑(尤其是处理`:_destroy`部分) (3认同)
  • 在帖子控制器的show动作中,我想你已经忘了@post = Post.find(params [:id]) (2认同)
  • @SSR 为什么要在“创建”操作中遍历每个帖子附件?Rails 和carrierwave 足够智能,可以自动保存集合。 (2认同)
  • 当我向post_attachment模型添加验证时,它们不会阻止保存post模型.而是保存帖子,然后仅为附件模型抛出ActiveRecord无效错误.我认为这是因为创造!方法.但是使用create而不是默默地失败.知道如何在帖子到达附件时进行验证吗? (2认同)

drj*_*nco 31

如果我们看一下CarrierWave的文档,这实际上非常简单.

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

作为一个例子,我将使用Product作为我想添加图片的模型.

  1. 获取主分支Carrierwave并将其添加到您的Gemfile:

    gem 'carrierwave', github:'carrierwaveuploader/carrierwave'
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在预期模型中创建一个列来托管图像数组:

    rails generate migration AddPicturesToProducts pictures:json
    
    Run Code Online (Sandbox Code Playgroud)
  3. 运行迁移

    bundle exec rake db:migrate
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将图片添加到型号产品中

    app/models/product.rb
    
    class Product < ActiveRecord::Base
      validates :name, presence: true
      mount_uploaders :pictures, PictureUploader
    end
    
    Run Code Online (Sandbox Code Playgroud)
  5. 在ProductsController中将图片添加到强参数中

    app/controllers/products_controller.rb
    
    def product_params
      params.require(:product).permit(:name, pictures: [])
    end
    
    Run Code Online (Sandbox Code Playgroud)
  6. 允许您的表单接受多张图片

    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 %>
    
    Run Code Online (Sandbox Code Playgroud)
  7. 在您的视图中,您可以引用解析图片数组的图像:

    @product.pictures[1].url
    
    Run Code Online (Sandbox Code Playgroud)

如果您从文件夹中选择多个图像,则顺序将是您从上到下的确切顺序.

  • CarrierWave解决这个问题让我感到畏缩.它涉及将文件的所有引用放入数组中的一个字段!它当然不会被视为"轨道方式".如果你想删除一些,或者在帖子中添加额外的文件怎么办?我不是说这是不可能的,我只是说它会很难看.连接表是一个更好的主意. (9认同)
  • 我不能同意托比.你能提供这样的解决方案吗? (3认同)
  • 该解决方案已由SSR提供.另一个模型用于保存上传的文件,然后需要上传的文件与其他模型存在一对多或多对多的关系.(我之前评论中提到的联接表是多对多关系的情况) (2认同)

Chr*_*ood 6

另外我想出了如何更新多个文件上传,我也重构了一下.这段代码是我的,但你得到了漂移.

def create
  @motherboard = Motherboard.new(motherboard_params)
  if @motherboard.save
    save_attachments if params[:motherboard_attachments]
    redirect_to @motherboard, notice: 'Motherboard was successfully created.'
  else
    render :new
  end
end


def update
  update_attachments if params[:motherboard_attachments]
  if @motherboard.update(motherboard_params)
    redirect_to @motherboard, notice: 'Motherboard was successfully updated.'
  else
   render :edit
  end
end

private
def save_attachments
  params[:motherboard_attachments]['photo'].each do |photo|
    @motherboard_attachment = @motherboard.motherboard_attachments.create!(:photo => photo)
  end
end

 def update_attachments
   @motherboard.motherboard_attachments.each(&:destroy) if @motherboard.motherboard_attachments.present?
   params[:motherboard_attachments]['photo'].each do |photo|
     @motherboard_attachment = @motherboard.motherboard_attachments.create!(:photo => photo)
   end
 end
Run Code Online (Sandbox Code Playgroud)


pro*_*ils 6

SSR的一些小补充回答:

accepts_nested_attributes_for不要求您更改父对象的控制器.所以如果要纠正

name: "post_attachments[avatar][]"
Run Code Online (Sandbox Code Playgroud)

name: "post[post_attachments_attributes][][avatar]"
Run Code Online (Sandbox Code Playgroud)

然后所有这些控制器变化都变得多余:

params[:post_attachments]['avatar'].each do |a|
  @post_attachment = @post.post_attachments.create!(:avatar => a)
end
Run Code Online (Sandbox Code Playgroud)

您还应该添加PostAttachment.new到父对象表单:

在views/posts/_form.html.erb中

  <%= f.fields_for :post_attachments, PostAttachment.new do |ff| %>
    <div class="field">
      <%= ff.label :avatar %><br>
      <%= ff.file_field :avatar, :multiple => true, name: "post[post_attachments_attributes][][avatar]" %>
    </div>
  <% end %>
Run Code Online (Sandbox Code Playgroud)

这将使父控制器中的这一更改变得多余:

@post_attachment = @post.post_attachments.build
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Rails fields_for表单未显示,嵌套表单

如果您使用Rails 5,则由于accepts_nested_attributes_for中的错误而将Rails.application.config.active_record.belongs_to_required_by_default值更改truefalse(在config/initializers/new_framework_defaults.rb中)(否则accepts_nested_attributes_for通常不会在Rails 5下工作).

编辑1:

添加about destroy:

在models/post.rb中

class Post < ApplicationRecord
    ...
    accepts_nested_attributes_for :post_attachments, allow_destroy: true
end
Run Code Online (Sandbox Code Playgroud)

在views/posts/_form.html.erb中

 <% f.object.post_attachments.each do |post_attachment| %>
    <% if post_attachment.id %>

      <%

      post_attachments_delete_params =
      {
      post:
        {              
          post_attachments_attributes: { id: post_attachment.id, _destroy: true }
        }
      }

      %>

      <%= link_to "Delete", post_path(f.object.id, post_attachments_delete_params), method: :patch, data: { confirm: 'Are you sure?' } %>

      <br><br>
    <% end %>
  <% end %>
Run Code Online (Sandbox Code Playgroud)

这样你就根本不需要拥有子对象的控制器!我的意思PostAttachmentsController是不再需要任何东西了.至于父对象的controller(PostController),你几乎也不会改变它 - 你唯一改变的是列入白名单的params(包括与子对象相关的params),如下所示:

def post_params
  params.require(:post).permit(:title, :text, 
    post_attachments_attributes: ["avatar", "@original_filename", "@content_type", "@headers", "_destroy", "id"])
end
Run Code Online (Sandbox Code Playgroud)

这就是为什么accepts_nested_attributes_for这么棒了.