无法使用回形针保存多个图像

时间:2014-09-10 10:33:24

标签: ruby-on-rails ruby paperclip

我希望能上传多张图片。 我正在使用本指南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

它完美地保存了表单,但是当我不想检查是否保存了任何图片时,它返回nil。

1 个答案:

答案 0 :(得分:1)

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

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