2014-09-10 63 views
0

我希望能够上传多张图片。 我正在使用本指南http://www.railscook.com/recipes/multiple-files-upload-with-nested-resource-using-paperclip-in-rails/无法使用回形针保存多个图像

我有模型可以附加多个图片的窗体。图片模型附有文件图像。 我的代码:

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 2014-09-10 11:46:29

回答

1

在您的图片模型的attr_accessible中添加form_id。

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

仍然没有保存..也没有显示任何错误消息。 – Edgars 2014-09-10 13:17:17

+1

你的图片表中有form_id。对? – 2014-09-10 13:25:27

+0

是的,我在图片表中有form_id。 – Edgars 2014-09-10 16:14:49