I am new to rails and am stuck on the above.
I have used a mixture of code from the agile web dev with rails book
and what I have found with google.
I realise there are easier ways to do this with various plugins but I
would be interested to know why my code does not work.
The code runs and a file is created in the expected place but this
file is zero length so something is wrong.
Model code
class Photo < ActiveRecord::Base
belongs_to :user
validates_format_of :content_type,
:with => /^image/,
:message => “— you can only upload pictures”
def uploaded_picture=(picture_field)
self.photofile = base_part_of
(picture_field.original_filename)
self.content_type = picture_field.content_type.chomp
self.is_visible = 0
@data = picture_field.read
end
etc etc
Controller code
def create
@photo = Photo.new(params[:photo])
filename = @photo.photofile
directory = “public/images”
# create the file path
user= User.find(session[:userid])
path = File.join(directory, user.user_id)
if File.exist?(path) == false
Dir.mkdir(path)
end
path = File.join(directory, user.user_id, filename)
# write the file
File.new(path, “wb”) { |f| f.write(params[:picture_field].read) }
File.new(path, "wb") { |f| f.write(@data) }
and the view
<% form_for(:photo,
:url => {:action => ‘create’},
:html => { :multipart => true }) do |f| %>
Caption
<%= f.text_field :caption %>
<%= f.submit "Upload Photo" %>
<% end %>So there are obviously some basics here that I have not yet “got”.
Many thanks for looking