2016-11-02 1 views
0

안녕하세요 아래 코드를 통해 하나 대신에 여러 사진을 업로드하고 싶습니다.클립 클립/활성 관리로 여러 이미지 업로드

은 내가 active adminpaperclip

내가 주변에 인터넷 검색 및 스택 오버플로에 다양한 게시물을 체크 아웃 한 작업이 아니라 미경 때죠 내 클라이언트 요청을 관리하는 방법을 잘 모르겠어요,하지만 난 못 찾았어요 해결책은 아직 없습니다. 어떤 제안이나 도움

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 

답변

3
입니다

나는 jQuery 파일 업로드와 같은 것을 사용할 것을 제안 할 것이다. 당신을 위해 파일 업로드를 처리 할 수 ​​있습니다.

그런 식으로 컨트롤러는 한 번에 하나의 파일 만 처리하지만 Ajax 호출을 통해 각 업로드가 개별적으로 처리되므로 한 번에 많은 파일을 업로드 할 수 있습니다.

다른 대안을 시도했지만 한 번에 두 개 이상의 파일을 서버에 게시하려고하면 서버 시간 초과 문제 (특히 heroku)가 발생합니다. 여기

당신이 구현에 대한 자세한 도움이 필요하면 알려주세요 https://github.com/tors/jquery-fileupload-rails

ActiveAdmin을

에 연결할 수있는 보석이다.

업데이트 : (상황에 대한 의견을 참조하십시오) 여기

활성 관리자의 코드를 구현하는 방법을 보여주는 몇 가지 예제 코드입니다. 나는 그것이 많은 코드처럼 보일 뿐이지 만, 단계별로 작업을하면 꽤 간단하다는 것을 알 수있을 것이다.

제품 모델 :

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 업로드가 많은 옵션을 얻는 곳입니다. 양식 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

그냥 참조를 위해 내가 만든 응용 프로그램은 레일을 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 %> 
+0

위대한! 고마워요. 오늘 밤 나중에 확인해 볼게요, 어떻게되는지 알려 드리겠습니다. – Slowboy

+0

안녕하세요 @veldtmana, 나는 보석을'gemfile'에 추가했지만'active admin'과 통합하는 방법을 모르거나 적어도 그렇게하는 방법을 찾을 수는 없습니다. 아마 구현을 안내해 주시겠습니까? 감사합니다 – Slowboy

+0

안녕하세요 @ Slowboy, 내가 당신을 위해 무엇인가 함께 빨리 집어 넣을 게요 – veldtmana