【问题标题】:Multiple image uploads with paperclip/active admin使用回形针/活动管理员上传多个图像
【发布时间】:2017-03-16 04:22:18
【问题描述】:

您好,我希望能够通过下面的代码为product 上传多张图片,而不是现在只上传一张。

我不确定如何管理我的客户请求,因为我对使用 active adminpaperclip 非常缺乏经验

我在 Stack Overflow 上搜索并查看了各种帖子,但我还没有找到解决方案。任何建议或帮助都会很棒....

这是product 模型

class Product < ActiveRecord::Base
  belongs_to :category
  belongs_to :label

  has_many :product_items, :dependent => :destroy

   extend FriendlyId
   friendly_id :title, use: [:slugged, :finders]


    validates :title, :description, presence: true
    validates :price_usd, :price_eu, numericality: {greater_than_or_equal_to: 0.01}
    validates :title, uniqueness: true


   has_attached_file :image, styles: { medium: "500x500#", thumb: "100x100#" }
   validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/


   def self.search(query)

   where("title LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%") 
  end
end

这是app/admin/product.rb

  ActiveAdmin.register Product do


  permit_params :title, :slug, :description, :stock_quantity, :image, :price_usd, :price_eu, :category_id, :label_id

  index do
      column :title
      column :slug
      column :category
      column :label
      column :created_at
      column :stock_quantity

      column :price_eu, :sortable => :price_eu do |product|
        number_to_currency(product.price_eu, :unit => " € " , :precision => 0) 
      end
      column :price_euro, :sortable => :price_usd do |product|
        number_to_currency(product.price_usd, :unit => " $ " , :precision => 0)
      end

      actions   

  end

form do |f|
        f.inputs do
        f.input :title
        f.input :slug
        f.input :description, as: :ckeditor, input_html: { ckeditor: { toolbar: 'Full' } }
        f.input :stock_quantity
        f.input :image
        f.input :price_usd
        f.input :price_eu
        f.input :category
        f.input :label
        end
        actions 
      end

end

这里是products_controller.rb

class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]


  def show
  @meta_title = "Samoli #{@product.title}"
  @meta_description = @product.description

  end

def search

@product = Product.search(params[:query]).order("created_at DESC")
@categories = Category.joins(:products).where(:products => {:id => @product.map{|x| x.id }}).distinct


end

private
# Use callbacks to share common setup or constraints between actions.
def set_product
  @product = Product.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def product_params
  params.require(:product).permit(:title, :description, :price_usd, :price_eu, :image, :category_id, :stock_quantity, :label_id, :query, :slug)
end
end

【问题讨论】:

    标签: ruby-on-rails ruby paperclip activeadmin image-uploading


    【解决方案1】:

    我建议使用类似 jQuery 文件上传的东西来为你处理文件上传。

    这样,您的控制器仍然一次只处理一个文件上传,尽管您可以一次上传多个文件,因为每个上传都是通过 Ajax 调用单独处理的。

    我尝试了其他替代方案,但尝试一次将多个文件发布到服务器,您很快就会遇到服务器超时问题(尤其是在 heroku 上)。

    这是一个可以连接到 ActiveAdmin 的 gem

    https://github.com/tors/jquery-fileupload-rails

    如果您在实施方面需要更多帮助,请告诉我。

    更新:(请参阅 cmets 了解上下文)

    这里是一些示例代码,说明了如何在活动管理员中实现代码。我知道它看起来像很多代码,但只要一步一步地完成它,你就会发现它非常简单。

    产品型号:

    class Product < ApplicationRecord
      has_many :photos
    end
    

    照片模型:

    class Photo < ApplicationRecord
      include ActionView::Helpers
    
      belongs_to :product
      has_attached_file :image, :styles => { large: "500x500>",thumb: "100x100>" }
      validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
    
      def thumb
        link_to(image_tag(image.url(:thumb)), thumb_url)
      end
    
      private
    
      def thumb_url
        Rails.application.routes.url_helpers.admin_product_photo_path(product, self)
      end
    end
    

    然后在活动管理员中执行以下操作。

    ActiveAdmin 产品:

    ActiveAdmin.register Product do
      permit_params :title
    
      form do |f|
        f.inputs do
          f.input :title
        end
        f.actions
       end
    
      index do
        column :title
        column :images do |product|
          product.photos.map do |photo|
            link_to (image_tag photo.image.url(:thumb)), [:admin, photo.product, photo]
          end.join.html_safe
        end
        actions
      end
    
      show do
        attributes_table
        panel "Images" do
          div class: "js-product_photos" do
            product.photos.map do |photo|
              link_to (image_tag photo.image.url(:thumb)), [:admin, photo.product, photo]
            end.join.html_safe
          end
          div do
            semantic_form_for [:admin, resource, Photo.new], multipart: true do |f|
              f.inputs do
                f.input :image, as: :file,
                                input_html: {
                                  class: 'js-photo_upload',
                                  type: "file",
                                  name: "photo[image]",
                                  multiple: true
                                }
              end
             end
          end
        end
      end
    end
    

    注意表单中定义的 html 选项。这就是 jQuery upload 派生出许多选项的地方。表单 url 也很重要。

    我可以在任何地方添加表单,但我认为它在产品展示页面上效果很好。

    ActiveAdmin 照片:

    ActiveAdmin.register Photo do
      belongs_to :product
      permit_params :image
    
      controller do
        def create
          create! do |format|
            format.json { render :json => {thumb: resource.thumb} }
          end
        end
      end
    
      show do
        attributes_table do
          row :product
          row :image do |product|
            image_tag product.image.url(:large)
          end
        end
      end
    end
    

    最后在active_admin.js.coffee

    #= require active_admin/base
    #= require jquery-fileupload/basic
    
    $ ->
      $('.js-photo_upload').fileupload dataType: 'json', done: (e, data) ->
        $('.js-product_photos').append data.result.thumb
    

    就是这样!选择文件后,文件应立即通过 AJAX 调用上传。上传后,图像标签将附加到图像列表中。您一次可以选择多个图像

    这实际上只是触及了基本的 jQuery 文件上传器可以做的事情的表面 - 在这里阅读更多关于它的信息。 https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin

    仅供参考,我构建的应用是 rails 5 应用,以下是对本示例很重要的宝石:

    gem 'activeadmin', github: 'activeadmin'
    gem 'inherited_resources', github: 'activeadmin/inherited_resources'
    gem 'devise'
    gem 'paperclip', "~> 5.0.0"
    gem "jquery-fileupload-rails" 
    

    更新:基于另一个问题

    现在您可以上传图片了,您可以在例如产品展示页面 (show.html.erb) 上显示它们:

    <h1><%= @product.title %></h1>
    <% @product.photos.each do |photo| %>
      <%= image_tag(photo.image.url(:large) %>  
    <% end %>
    

    【讨论】:

    • 太棒了!谢谢,今晚晚些时候我会检查一下,我会告诉你情况如何。
    • 嗨@veldtmana,我将gem添加到gemfile,但我不确定如何将它与active admin集成,或者至少我找不到足够好的指导如何做到这一点.您能否指导我实施。谢谢
    • 嗨@Slowboy,我会很快为你整理好东西
    • 非常感谢@veldtmana,那太好了,我一整天都陷入了困境
    • @Slowboy 这里是一个示例实现 - 如果有任何不清楚的地方请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2014-08-24
    相关资源
    最近更新 更多