【问题标题】:Uploading more than one image using paperclip and active admin使用回形针和活动管理员上传多个图像
【发布时间】:2017-08-03 07:18:15
【问题描述】:

我需要在我正在构建的应用中向产品上传多个图片。 图片通过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

第三次更新

好的,我在def product_params 末尾添加了下面的images_attributes: 剪辑到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

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

另一个更新

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

在位于索引页面的 sn-p 中,显示了每个类别的最新上传。查看应用程序如何循环浏览产品并向每个产品显示相应的图像。现在我从索引文件中的这一行 &lt;%= image_tag product.image.url(:medium), class: "img-responsive" %&gt; 收到错误。

<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>  

【问题讨论】:

    标签: jquery ruby-on-rails ruby activeadmin


    【解决方案1】:

    正如您所拥有的那样,该模型只能在其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
    

    我只能带你到这里,因为你没有发布任何控制器、查看代码或 active_admin 设置,但是你只需要read railsactive_admin documentation on nested resources 以便你可以弄清楚如何编写嵌套表单让您可以为您的产品创建这些图像。

    更新:如果“进一步了解这个答案”是指“为你编写代码”,那么,不。这里和active_admin documentation on nested resources 中有足够的信息供您了解。但是,如果其中任何一个令人困惑,我可以提供澄清。

    【讨论】:

    • 非常感谢@DiegoSalazar,我之前不小心发送了一个未完成的问题:)。现在我添加了活动管理模型、产品控制器和视图。如果您能进一步回答,那就太好了。
    • 我迫不及待地想看看@DiegoSalazar 是否会进一步回答,因为您提供了所有丢失的文件@DaudiHell。我对“回形针”也有类似的问题
    • 我完全理解你不想为我写这个,我也不想那样,我不知道我会从中学到什么:) 我做了image.rb 模型并将has_manybelongs_to 关系添加到两个模型。目前我不确定product_controller.rb 的外观,因为我将所有图像逻辑添加到了一个新模型image.rbmodel。我必须为 image.rb 模型创建新的控制器吗?
    • 请查看问题中的另一个更新
    • 除了允许新嵌套字段的强参数外,您无需更改控制器的大部分内容。并将accepts_nested_attributes_for :images 声明添加到您的Product 模型中。您可以在我上面链接的Rails nested forms 文档中阅读所有相关信息。
    猜你喜欢
    • 2017-03-16
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2014-08-24
    相关资源
    最近更新 更多