2014-09-10 4 views
0

여러 사진을 업로드하고 싶습니다. 이 가이드를 사용 중입니다. http://www.railscook.com/recipes/multiple-files-upload-with-nested-resource-using-paperclip-in-rails/클립을 사용하여 여러 이미지를 저장할 수 없습니다.

여러 사진을 첨부 할 수있는 Form이라는 모델이 있습니다. 그림 모델에 첨부 파일 이미지가 있습니다. 내 코드 :

Form.rb

class Form < ActiveRecord::Base 
     attr_accessible :defect, :region, :pictures  
     has_many :pictures, :dependent => :destroy 
end 

Picture.rb

class Picture < ActiveRecord::Base 
    # attr_accessible :title, :body 

    belongs_to :form 
    attr_accessible :image 
    has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png" 
    validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ 


end 

_form.html.erb

<%= form_for @form, :html => { :class => 'form-horizontal', multipart: true } do |f| %> 
    <div class="control-group"> 
    <%= f.label :name, :class => 'control-label' %> 
    <div class="controls"> 
     <%= f.text_field :defect, :class => 'text_field' %> 
    </div> 
    </div> 
    <div class="control-group"> 
    <%= f.label :region, :class => 'control-label' %> 
    <div class="controls"> 
     <%= f.text_field :region, :class => 'text_field' %> 
    </div> 
    </div> 

    <div class="control-group"> 
    <%= f.label :pictures, :class => 'control-label' %> 
    <div class="controls"> 

     <%= file_field_tag "images[]", type: :file, multiple: true %> 
    </div> 
    </div> 

    <div class="form-actions"> 
    <%= f.submit nil, :class => 'btn btn-primary' %> 
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")), 
       forms_path, :class => 'btn btn-mini' %> 
    </div> 
<% end %> 

양식 컨트롤러

def create 
    @form = Form.new(params[:form]) 

    respond_to do |format| 
    if @form.save 

     if params[:images] 
     #===== The magic is here ;) 
     params[:images].each { |image| 
      @form.pictures.create(image: image) 
     } 
     end 

     format.html { redirect_to @form, notice: 'Form was successfully created.' } 
     format.json { render json: @form, status: :created, location: @form } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @form.errors, status: :unprocessable_entity } 
    end 
    end 
end 

그것은 완벽 양식을 저장하지만 내가 확인 wan't 때 어떤 그림이 전무를 반환 저장합니다.

+1

http://stackoverflow.com/a/18921699/2231236이 http://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/ – Nithin

답변

1

사진 모델의 attr_accessible에 form_id를 추가하십시오.

class Picture < ActiveRecord::Base 
    ..... 
    attr_accessible :image, :form_id 
    ..... 
end 
+0

아직 저장하지 않았습니다. 오류 메시지도 표시되지 않습니다. – Edgars

+1

사진 테이블에 form_id가 있습니다. 권리? –

+0

예, 나는 그림 테이블에 form_id가 있습니다. – Edgars

관련 문제