使用回形针和活动管理员上传多张图片

Uploading more than one image using paperclip and active admin

我需要向正在构建的应用中的产品上传多张图片。 图片是通过 ActiveAdminpaperclip

上传的

上传一张没问题,上传多张就不行了。

我试过使用 jquery-fileupload-railsgem,它应该连接到 active admin,但没有成功。

我也在网上搜索过这个问题,并在 Stack Overflow 上查看了很多帖子,但我还没有找到解决方案。

这里是产品型号product.rb

class Product < ActiveRecord::Base
  acts_as_list :scope => [:category, :label]
  belongs_to :category
  belongs_to :label

  has_many :product_items, :dependent => :destroy

    validates :title, :description, presence: true
    validates :price_usd, :price_eur, 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/

end

第三次更新

好的,我将下面的 images_attributes: 片段添加到 def product_params

末尾的 products_controller.rb
def product_params
      params.require(:product).permit(:title, :description,...., images_attributes: [:image , :id , :_destroy])
end

我在 admin/product.rb 中添加了

            f.has_many :images , heading: false, allow_destroy: true do |ff|
            ff.input :image, required: true, as: :file
             end

现在我可以通过活动管理员 select 图片,但它不会保存到数据库中。

另一个更新

这里是app/views/pages/index.html.erb

在位于索引页上的该片段中,显示了每个类别中的最新上传。查看应用程序如何遍历产品并为每个产品显示相应的图像。现在我从索引文件中的这一行 <%= image_tag product.image.url(:medium), class: "img-responsive" %> 得到错误。

<div class="container-fluid">

    <% @products.each_slice(3) do |products_group| %>
            <div class="row">
              <% products_group.each do |category, products| %>

                    <% products.each_with_index do |product, index| %>
                        <% if index == 0 %>
                            <div class="col-lg-4 col-sm-6 col-xs-12 center-block " >

                            <%= link_to category_path (category), { :method => 'GET' } do %>
                                <%= image_tag product.image.url(:medium), class: "img-responsive" %>
                            <% end %>
                    <div class="caption">
                        <p class="category-name" ><%= product.category.name %></p>
                     </div> 
                    <% end %>
                    <% end %>
                    </div> 
                <% end %>
                </div>
            <% end %>

    </div>

更新

here is the `products_controller.rb`

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

  def show
   offset = rand(100)
   @products_rand = Product.where(category_id: 
   @product.category_id).order("RANDOM()").limit(6)
  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_eur, :image, :category_id, :stock_quantity, :label_id, :query, :slug)
end 
end

这是 Active admin 产品模型 admin/product.rb

    ActiveAdmin.register Product do

  config.sort_order = 'position_asc' # assumes you are using 'position' for your acts_as_list column
  config.paginate   = true # optional; drag-and-drop across pages is not supported

  sortable # creates the controller action which handles the sorting

permit_params :title, :slug, :description, :stock_quantity, :image, :price_usd, :price_eur, :category_id, :label_id,  images_attributes: [:image , :id , :_destroy]

    index do
         sortable_handle_column # inserts a drag handle
        column :title
        column :slug
        column :category
        column :label
        column :created_at
        column :stock_quantity

        column :price_eur, :sortable => :price_eur do |product|
            number_to_currency(product.price_eur, :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 multipart: true do |f|
            f.inputs "Product Details" do
            f.input :title
            f.input :slug
            f.input :description, as: :ckeditor, input_html: { ckeditor: { toolbar: 'Full' } }
            f.input :stock_quantity
            f.input :image, required: false
            f.input :price_usd
            f.input :price_isl
            f.input :category
            f.input :label
            end
            f.actions   
          end

end

最后是产品视图,`app/views/products/show.html.erb``

    <div class="container">  
     <div class="row product_top text-center">
      <div class="col-xs-12 col-sm-6 center-block">
       <div class="product_description">

        <h3 class="title"><%= @product.title %></h3>
        <p class="label-product"><%= @product.label.name %></p>

        <p class="description">Description</p>

        <p class="product-description"><%= @product.description.html_safe %></p>

            <% if @product.stock_quantity <= 0 %>
               <p> Out of stock </p> 
            <% end %>
     </div>
        <div class="col-xs-12">
         <p class="product-price"> Price:</p> <%= number_to_currency(@product.price_usd, :unit => "€ " , :precision => 0) %> | <%= number_to_currency(@product.price_isl.to_i, :unit => "IKR " , :precision => 0) %>
        </div>

       <%# if @product.stock_quantity >= 1 %>
        <div class="row text-center add-cart-wrapper">  
          <% if @product.stock_quantity >= 1 %>
          <%= link_to 'Add to Cart', product_product_items_path(@product), :method => :post, class: 'add-to-cart'%>
         <% end %>
       </div>
    </div>  
   <div class="col-xs-12 col-sm-6 center-block" > 
    <%= image_tag @product.image.url(:medium), class: "img-responsive center-block"  %>

  </div>
  </div>  

  <div class="row product-teaser">

  <h4 class="text-center teaser-text"> similar products to <%= @product.title %> : </h4>
   <% @products_rand.each do |product| %>
      <div class="col-sm-2 col-xs-3 center-block product-thumbs-product-view" >

  <%= link_to product_path (product) do %>
                <%= image_tag product.image.url, :size => "100%x100%", class: "img-responsive center-block" %>
            <% end %>

          <h5 class="text-center"><%= link_to product.title, product, class: "text-center" %></h5>

      </div>
    <% end %>

  </div>

   </div>  

您拥有的那个模型只能在其 image 属性中保存一个文件上传。您需要为您的产品添加一个 has_many 关联,以便它可以有很多文件。

即创建一个将保存附件并与产品相关联的图像模型:

rails g model Image product_id:integer image_file_name:string image_file_size:integer image_content_type:string
rake db:migrate

然后将产品关联到它:

class Product < ActiveRecord::Base
  has_many :images
  # ... the rest of your code...
end

并将附件声明移动到您的图像模型中:

class Image < ActiveRecord::Base
  belongs_to :product

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

现在您可以将许多图像与一个产品相关联:

product = Product.new
product.images.build image: File.open('some/image/for/example.jpg', ?r)
product.save
product.images.first.image # the Paperclip::Attachment object

由于您没有 post 任何控制器、视图代码或 active_admin 设置,所以我只能带您走这么远,但是,您只需要 read rails or active_admin documentation on nested resources 这样您就可以弄清楚如何编写一个嵌套表单,让您可以为您的产品创建这些图像。

更新:如果"taking this answer further"是指"write the code for you"那么,不是。这里和 active_admin documentation on nested resources 中有足够的信息供您理解。但是,如果其中任何一个令人困惑,我可以提供澄清。