2011年6月9日木曜日

Rails:ファイルの添付の覚書(DBへではなく、ファイルを保存)その1

Railsでファイルのアップロードの覚書

プラグイン(attacument_fu,paperclipedなど)を使わない方法

下記のコード例は、1画面で複数ファイルをアップロードする場合の例です。

VIEW

_from.html.erb



<% form_for @message , :url => { :action => action }, :html => {  :multipart => true, :id => 'message_form', :name => :message_form } do |f| %>
     :
      <% @message.attachments.each do |attach| %>
        <% if attach.id %>
          <% f.fields_for :attachments, attach do |attachment_form| %>
            <%= attachment_form.hidden_field :id %>
            <%= attachment_form.text_field :name %>
            Delete:<%= attachment_form.check_box :_destroy %><br />
          <% end %>
        <% else %>
          <% f.fields_for :attachments, attach do |attachment_form| %>
            <p>
            <%= attachment_form.hidden_field :id %>
            <%= attachment_form.label :path %>
            <%= attachment_form.file_field(:upload_data) %>
            </p>
          <% end %>
        <% end %>
      <% end %>
      :


Controller

    upload_files ||= []
    params[:message][:attachments_attributes].values.each do |attach|
      upload_file = attach[:upload_data]

      if upload_file
        upload_files << upload_file
      end

    end if params[:message][:attachments_attributes]

    respond_to do |format|
      if @message.save

        Dir.mkdir("#{Settings.upload_dir}#{@message.id}") if upload_files.count > 0
        upload_files.each do |upload_file|
          File.open("#{Settings.upload_dir}#{@message.id}/#{upload_file.original_filename}", "w+") { |f| f.write upload_file.read }
      end

0 件のコメント:

コメントを投稿