Hello, I'm just starting to learn ruby on rails and I have a problem uploading pictures to my server.
I just want to store the url of the picture and upload its file to public/images when I create a new Picture record. I don't know where is my error and I am going crazy. I don't need it for any customer or similar, I only want to understand why it doesn't work. Please help!
I have used this tutorial: http://programming-ut.blogspot.com/2010/01/ruby-on-rails-file-upload.html
I have two tables:
Dog - name - weight ...
Picture - url - dog_id
Dog has many Picture Picture belong to Dog
In picture_controller I just call a method 'upload' of the model at creation:
def create @picture = Picture.new(params[:picture]) post = Picture.upload(params[:picture],@picture) respond_to do |format| if @picture.save format.html { redirect_to(@picture, :notice => 'Created!') } format.xml { render :xml => @picture, :status => :created, :location => @picture } else format.html { render :action => "new" } format.xml { render :xml => @picture.errors, :status => :unprocessable_entity } end end end
The method code is:
class Picture < ActiveRecord::Base belongs_to :dog def self.upload(data,insert) fullname = data['url'].original_filename name = File.basename(fullname) name.sub(/[^\w\.\-]/,'_') insert.url = name directory = "/public/images" path = File.join(directory, insert.url) File.open(path, "wb") { |f| f.write(data['url'].read) } end end
And the view:
<h1>New picture</h1> <% form_for(@picture, :html => {:multipart => true}) do |f| %> <%= f.error_messages %> <p> <%= f.label :url %><br /> <%= f.file_field :url %> </p> <p> <%= f.label :perro_id %><br /> <%= f.text_field :perro_id %> </p> <p> <%= f.submit 'Create' %> </p> <% end %> When I push button Create, the log shows:
Processing PicturesController#create (for 83.44.0.216 at 2010-12-11 21:16:49) [POST] Parameters: {"commit"=>"Create", "authenticity_token"=>"oZTzcJa99hTRHHl9hGSTEG70cbLITHt58wkNZIMlFo4=", "picture"=>"perro_id"=>"", "url"=>#<File:/tmp/RackMultipart20101211-28729-1ev718o-0>}}
Errno::ENOENT (No such file or directory - /public/prueba): app/models/picture.rb:26:in `initialize' app/models/picture.rb:26:in `open'
If you have read to this point... I can only say thanks!