2011-03-22 4 views
2

Rails 3 및 Paperclip을 사용하여 다형성 연결을 사용하여 업로드 된 파일을 여러 객체 유형에 연결하고 있습니다.Rails 3 Paperclip Uploadify : 객체 저장 전에 업로드 된 객체 첨부 파일 저장

# app/models/asset.rb 
class Asset < ActiveRecord::Base 
    # Nothing here yet 
end 

# app/models/image.rb 
class Image < Asset 
    belongs_to :assetable, :polymorphic => true 
    has_attached_file :file, { 
    :styles => { 
     :small => { :geometry => '23x23#', :format => 'png' }, 
     :medium => { :geometry => '100x100#', :format => 'png' } } 
    }.merge(PAPERCLIP_STORAGE_OPTIONS).merge(PAPERCLIP_STORAGE_OPTIONS_ASSET_IMAGE) # Variables sent in environments to direct uploads to filesystem storage in development.rb and S3 in production.rb 
    validates_attachment_presence :file 
    validates_attachment_size :file, :less_than => 5.megabytes 
end 

내가 그때와 같은 여러 이미지를 첨부하고 다른 객체 유형, 단위를 가지고 다음과 같이 내가 (나중에 비디오 및 문서와 같은 다른 사람을 추가 할 예정) 자산 모델과 상속 이미지 모델을 만들었습니다 다음과 같습니다 :

# app/models/unit.rb 
class Unit < ActiveRecord::Base 
    # ... 

    has_many :images, :as => :assetable, :dependent => :destroy 
    accepts_nested_attributes_for :images 

end 

# app/controllers/units_controller.rb 
class UnitsController < ApplicationController 
    # ... 

    def new 
    @unit = current_user.units.new 
    # ... 
    @unit.images.build 
    end 

    def create 
    @unit = current_user.units.new(params[:unit]) 
    # ... 
    respond_to do |format| 
     if @unit.save 
     format.html { redirect_to(@unit, :notice => 'Unit creation successful!') } 
     else 
     format.html { render :action => "new" } 
     end 
    end 
    end 

    def show 
    @unit = current_user.units.find(params[:id]) 
    @unit_images = @unit.images 
    # ... 
    end 

    def edit 
    @unit = current_user.units.find(params[:id]) 
    # ... 
    @unit.images.build 
    end 

    def update 
    @unit = current_user.units.find(params[:id], :readonly => false) 

    respond_to do |format| 
     if @unit.update_attributes(params[:unit]) 
     format.html { redirect_to(@unit, :notice => 'Unit was successfully updated.') } 
     else 
     format.html { render :action => "edit" } 
     end 
    end 
    end 

    def destroy 
    @unit = current_user.units.find(params[:id]) 
    @unit.destroy 

    respond_to do |format| 
     format.html { redirect_to(units_url) } 
    end 
    end 

end 

# app/views/units/_form.html.haml 
.field # Display already uploaded images 
    = f.fields_for :images do |assets| 
    - unless assets.object.new_record? 
     = link_to(image_tag(assets.object.file.url(:medium)), assets.object.file.url(:original)) 
.field # Display field to add new image 
    = f.fields_for :images do |assets| 
    - if assets.object.new_record? 
     = assets.label :images, "Image File" 
     = assets.file_field :file, :class => 'uploadify' 

이러한 설정을 사용하여 양식 표시 당 한 번에 이미지를 업로드 할 수 있습니다.

여러 파일 업로드/미리보기를 추가하려면 Uploadify를 통합하려고 할 때 문제가 발생합니다. 모든 Uploadify 의존성을 만족하지만 Unit 모델과 관련된 이미지를 저장하기 위해 어떻게 든 다형성 연관이 제대로 이루어질 수 있도록 unit_id에 경외감을 포함시켜야합니다. 내가 쉽게 따라 종이 클립으로 업로드 할 수 있으며, Uploadify 작동하지 않습니다 동안

%script 
    $(document).ready(function() { 
    $('.uploadify').uploadify({ 
     uploader  : '/uploadify/uploadify.swf', 
     cancelImg  : '/uploadify/cancel.png', 
     auto   : true, 
     multi   : true, 
     script   : '#{units_path}', 
     scriptData  : { 
     "#{key = Rails.application.config.session_options[:key]}" : "#{cookies[key]}", 
     "#{request_forgery_protection_token}" : "#{form_authenticity_token}", 
     } 
    }); 
    }); 

그래서 : 다음은 내 현재 Uploadify 코드입니다. 어떤 도움이라도 대단히 감사 할 것입니다. 미리 감사드립니다.


UPDATE : Rails3, S3, Paperclip Attachment as it's own model? :

나는 비슷한 문제로이 댓글 가로 질러 더 많은 연구를하고 후. 이 상황에서 그게 효과가있을 지 여부에 대한 생각? /new 메서드에서 unit.id을 확인하고 Uploadify가 만든 애셋에 전달하는 쉬운 방법이 있습니까?

답변

4

상태 머신을 사용하여 draft 상태에서 양식을로드 할 때 바로 모델을 저장함으로써 매우 유사한 문제를 한 번 해결했습니다. 이 모델은 업로드중인 파일을 첨부하려고 할 때 사용할 수 있으며 나머지 양식을 제출하면 기본적으로 상태를 변경하는 모델을 업데이트하는 것입니다. published. 컨트롤러 등을 업데이트하는 것은 약간의 작업이지만 트릭을 수행했습니다.

+0

나는 그 접근법을 좋아하고 구현 중이다. 그러나 모델을 '초안'상태로 저장할 때 필요한 속성에 대해 무엇을 했습니까? 예를 들어, 필자는 여러 가지 validate_presence_of 문을 만족해야한다. 유효성 검사를 건너 뛰는 쉬운 방법이 있습니까? – theandym

+1

우리는'on update' 만 검증함으로써이 문제를 해결했습니다 :'validates_presence_of : foobar, : on => : update' – polarblau

관련 문제