如何使用回形针上传多个图像

时间:2016-05-06 03:13:58

标签: ruby-on-rails image upload paperclip

我正在创建一个具有模型" Gallery"的应用程序。我正在使用另一个模型,即#GalleryTehoto"。关系是:Gallery has_many GalleryPhotoGalleryPhoto belongs_to Gallery

以下是我创建的模型:

class Gallery < ActiveRecord::Base
  has_many :gallery_photos, dependent: :destroy
end

class GalleryPhoto < ActiveRecord::Base
  belongs_to :gallery
  has_attached_file :photo
  validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png']
end

现在我在创建图库后,在其索引页面上,我有链接添加将打开页面添加照片的照片。在此页面上,我将能够使用回形针添加照片。

这是我对gallery_photo的new.html.erb:

<%= form_for @gallery_photo,html: { multipart: true},url: gallery_photos_path,method: :post do |f| %>

              <%= f.hidden_field :gallery_id, value: params[:gallery_id]%>
              <%=f.file_field :photo%>
              <%= f.submit "Start Upload",class: "btn btn-primary actions"%>
        <% end %>

我可以上传单张照片。但我不知道如何使用回形针上传多张照片。任何帮助我都会感激。

1 个答案:

答案 0 :(得分:0)

这是我的代码,可以很好地使用paperclip上传多个文件: 我们可以使用嵌套属性或使用普通的简单方法来实现。

以下代码显示了常规方法:

User.rb

  

has_many:images,:dependent =&gt; :破坏

Image.rb

  

has_attached_file:avatar,:styles =&gt; {:medium =&gt; “300×300&gt;” 中}

     

belongs_to:user

用户/视图/ new.html.erb

<%= form_for @user, :html => { :multipart => true } do |f| %>

...... 
 ....

<%= file_field_tag :avatar, multiple: true %>

<% end  %>

Users_controller:

.....

    if @user.save
     # params[:avatar] will be an array.
     # you can check total number of photos selected using params[:avatar].count
      params[:avatar].each do |picture|      

        @user.images.create(:avatar=> picture)
        # Don't forget to mention :avatar(field name)

      end
    end

多数民众赞成。图片上传了。

相关问题