使用fields_for&回形针多文件更新

时间:2013-04-18 02:06:22

标签: ruby-on-rails paperclip

我正在尝试使用paperclip gem将多个文件上传到S3,并参考this教程。我有两个问题 1. upload标签只渲染一次,而不是控制器中指定的6次。 2.其次,每当我尝试编辑文档时,我都会收到以下错误。

  

DocumentsController中的ActiveRecord :: UnknownAttributeError#edit

     

未知属性:document_id

有任何建议如何解决这个问题?

模型/ Document.rb

class Document < ActiveRecord::Base
  attr_accessible :documentId, :name, :notes, :user_id

  belongs_to :user
  has_many :photos, :dependent=>:destroy
  accepts_nested_attributes_for :photos

  acts_as_taggable

  validates :name, :length => {:minimum =>3}
  validates_date :dtReminder, :on_or_after => lambda { Date.current }, :allow_blank => true


  validates_associated :user
  validates_uniqueness_of :name, :scope => :user_id
end

模型/ Photo.rb

class Photo < ActiveRecord::Base
  belongs_to :document


  has_attached_file :image, :style =>{:thumb => '150x150#',
          :medium => '300x300>',
          :large => '600x600>'
  }

  validates_attachment_size :photo, :less_than => 500.kilobytes

end

控制器/ document_Controller.rb

    def new
        @document = Document.new
        @document.user = current_user
        5.times {@document.photos.build}

        respond_to do |format|
          format.html # new.html.erb
          format.json { render json: @document }
        end
      end

def create
    @document = Document.new(params[:document])
    @document.user = current_user
    5.times {@document.photos.build}

    respond_to do |format|
      if @document.save
        format.html { redirect_to user_documents_path(current_user), notice: 'Document was successfully created.' }
        format.json { render json: @document, status: :created, location: @document }
      else
        format.html { render action: "new" }
        format.json { render json: @document.errors, status: :unprocessable_entity }
      end
    end
  end

查看/文档/ _form.html.erb

<%= form_for(document) do |f| %>

        <table>
                <tr>
                        <td><%= f.label :name %></td>
                        <td><%= f.text_field :name %></td>
                </tr>
                <tr>
                        <td><%= f.label :notes  %></td>
                        <td><%= f.text_area :notes %></td>
                </tr>
                <tr>
                                         <td>Photos</td>
                        <td>
                                <%= fields_for :photos do |photo|%>
                                        <%= photo.file_field :image%>
                                <%end%>
                        </td>

                </tr>
                <tr>
                        <td></td>
                        <td><%= f.submit %></td>
                </tr>
        </table>
<% end %>

1 个答案:

答案 0 :(得分:0)

对于多个图片上传字段,请查看Ryan Bate关于非常相似主题的截屏视频。

http://railscasts.com/episodes/73-complex-forms-part-1

http://railscasts.com/episodes/74

http://railscasts.com/episodes/75