2011-01-26 8 views
6

멀티 파트 양식에서 유효성 검사를 사용하는 여러 첨부 파일의 레일 3 예가 있습니까? 이 작업을 영원히 계속하기 위해 노력해 왔습니다. 모든 블로그 게시물과 메시지를 찾을 수 있었지만 아무도이 상황을 다루지 못했으며 문서는 전혀 도움이되지 않습니다.클립, 여러 첨부 파일 및 유효성 확인

첫 번째 문제는 대부분의 예제에서 'new_record'를 사용한다는 것입니다. 뷰 템플릿에서는 모델 인스턴스가 저장되지 않았기 때문에 유효성 검사가 실패 할 때 항상 새로운/생성 시퀀스에서 true를 반환합니다 (따라서 'id'값이 없음). 따라서 5 개의 모델 인스턴스/파일 입력으로 시작하여 하나의 파일을 업로드하면 새보기를 다시 렌더링 할 때 6 개의 파일 입력이 표시되고 같은 이유로 'unless'절이 실패하고 축소판이 표시되지 않습니다.

다른 필수 입력란에 대한 유효성 검사 오류를 사용자에게 표시하면서 업로드 된 파일에 대한 링크를 유지하려고합니다 (그리고 이것이 가능하다는 것을 알고 있습니다 - 임시 디렉토리에 있습니다).

누군가 어딘가에 종이 클립으로 작업해야합니다. ;)

+0

, 당신이 이제까지 무엇을 알게 되었습니까? 감사. –

+0

Paperclip에 대한 내용은 아니지만 적어도 전체 솔루션은 아닙니다 (유효성 검사없이 여러 첨부 파일 지원은 http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads에서 볼 수 있습니다). 나는 Sinatra 앱과 비슷한 것을 나중에 코딩했는데, 제대로 잡으려면 오랜 시간이 걸렸습니다. 잠시 동안 나는 사용자를 위해이 지원을 제공하지 않을 것입니다. (내 양식의 다른 필드에 대한 유효성 검사가 실패하면 다시 업로드해야합니다.) 저는 이것이 "80 %"솔루션을 사용할 때의 도전이라고 생각합니다. 확장보다는 처음부터 코딩하는 것이 더 쉽습니다. –

답변

1

세 가지 모델과 약간의 컨트롤러 매직을 사용하여이 작업을 수행 할 수 있습니다.

첫 번째 모델은 실제로 원하는 모델입니다. 전기를 봅시다.

class Biography < ActiveRecord::Base 
    has_one :biography_fields 
    has_many :biography_attachments 
end 

class BiographyFields < ActiveRecord::Base 
    belongs_to :biography 

    # Validations 
end 

class BiographyAttachment < ActiveRecord::Base 
    belongs_to :biography 

    # Paperclip stuff 
end 

지금 컨트롤러에이 같은 일을 할 수 있습니다

class BiographiesController 

    def some_method 
    @biography = Biography.find(params[:biography_id]) || Biography.create! 

    if @biography.biography_data.create(params[:biography_data]) 
     # Try to save the uploads, if it all works, redirect. 
    else 
     # Still try the uploads, if they work, save them and make sure to pass the :biography_id as a hidden field so they can be used without re-uploading. Also reflect this in the form. 
    end 
    end 

end 
4

방법 내가 사용 :

나는 많은 사진이 그 속성이 (10시). 속성 컨트롤러에서

:이 어디 갔지 코드에가는

def new 
    @search = Property.search(params[:search]) 
    @property = Property.new 
    10.times { @property.photos.build }  

    respond_to do |format| 
     format.html # new.html.erb 
     format.xml { render :xml => @property } 
    end 
    end 

    # GET /properties/1/edit 
    def edit 
    @search = Property.search(params[:search]) 
    @property = Property.find(params[:id]) 

    # Se o usuário atual for dono da propriedade 
    if current_user.id == @property.user_id 
     @photos = Photo.where("property_id = ?", @property.id) 
     @N = @photos.count 
     @N = [email protected]  
     @N.times { @property.photos.build } 
    else 
     render :action => "show" 
    end 

    end 

10.times이보기에 10 배 사진 필드를 "렌더링". 편집 양식에서 사진 필드 만 남겨 둡니다. 예 : 처음으로 사진 3 장을 업로드 한 후 더 업로드하려면 7 개의 필드 만 표시됩니다. 속성 모델에서


나는이 :

class Property < ActiveRecord::Base 
    attr_accessible :photos_attributes, :logradouro, :complemento, :wc, :negocio, :cep, :vagas, :valor, 
    :quartos, :uf, :area, :bairro, :suites, :salas, :numero, :cidade, :descricao, 
    :status, :tipoImovel 
    has_many :photos 
    accepts_nested_attributes_for :photos, :allow_destroy => true 

end 

이 사진을 업로드 할 수 있습니다.


사진 모델 : 일부 내 양식에

class Photo < ActiveRecord::Base 
    belongs_to :property  

    has_attached_file :photo, :styles => { :small => "100x100>", :medium => "530>x530", :large => "800x800>" } 
    validates_attachment_presence :photo 
    validates_attachment_size :photo, :less_than => 500.kilobytes 
end 

는 :

<div id="new_up">    
      <%= f.fields_for :photos do |p| %> 
       <% if p.object.new_record? %> 
        <p><%= p.file_field :photo %> 
         <%= p.radio_button :miniatura, true -%> 
        </p> 
        <% end %> 
      <% end %> 
      </div> 

     <div id="old_up"> 
      <h4>Imagens Atuais</h4> 
      <% f.fields_for :photos do |p| %> 
       <% unless p.object.new_record? %> 
        <div style="float: left;"> 
         <%= p.radio_button :miniatura, true -%> 
         <%= link_to image_tag(p.object.photo.url(:small)), p.object.photo.url(:original) %> 
         <%= p.check_box :_destroy %>    
        </div> 
       <% end %> 
      <% end %> 
     </div>