かぴぶろぐ

またかぴったかと思った・・・(´A`;)

Ruby on Railsの勉強

カテゴリ[ Ruby on Rails ]
ファイルアップロードサンプル
Schema
ActiveRecord::Schema.define(:version => 1) do

  create_table "sources", :force => true do |t|
    t.string   "filename"
    t.text     "content"
    t.string   "url"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

app/views/new.html.erb
<%= error_messages_for :source %>

<% form_for(@source, :html => {:multipart => true}) do |f| %>
  <p>
    <b>Filename</b><br />
    <%= f.text_field :filename %>
  </p>

  <p>
    <b>Content</b><br />
    <%= f.text_area :content %>
  </p>

  <p>
    <b>Url</b><br />
    <%= f.file_field :url %>
  </p>

  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>

<%= link_to 'Back', sources_path %>
app/controllers/sources_controller.rb
  # POST /sources
  # POST /sources.xml
  def create
    @source = Source.new(params[:source])
    @filename = params[:source]['url'].original_filename

    pp @filename

    if @filename != ""
        @source.url = "./files/" + @filename
        # save時にファイルをアップロード
        Source.save(params[:source]['url'])
    end

    respond_to do |format|
      if @source.save
        flash[:notice] = 'Source was successfully created.'
        format.html { redirect_to(@source) }
        format.xml  { render :xml => @source, :status => :created, :location => @source }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @source.errors, :status => :unprocessable_entity }
      end
    end
  end
app/models/source.rb
class Source < ActiveRecord::Base

    def self.save(url)

        File.open("public/files/#{url.original_filename}", "wb"){ |f|
            f.write(url.read) }
    end

end
参考URL

http://kapi.jp/kapi_blog/119

2008年02月16日

関連カテゴリ Ruby on Rails

この記事のコメント

この記事にコメントする