Hello everybody!
So this is likely a complete n00bish question as I only started riding
the rails last Wednesday, but I have been tearing my hair out over
this one for a number of hours now.
I created a model/table Picture/pictures and followed the guide at
Peak Obsession for uploading the file.
I have a field “path” which is to be the location relative to “public”
of the picture. The idea is that the filename is taken from what is
originally uploaded (in my case, ‘dog.png’). The database is
successfully updated with the path, but whenever I try:
script/runner ‘puts Picture.find_by_id(34).path’
I just get nil. I know that it works otherwise, since switching out
path for name (another one of the saved fields) works just fine.
Here are some snippets of my code:
picture.rb
def file=(incoming_file)
@temp_file = incoming_file
@filename = sanitize_filename incoming_file.original_filename
@content_type = incoming_file.content_type
@path = ‘/pictures/’ + @filename
end
before_save :set_path
attr_reader :filename
attr_accessor :path
def after_save
if @temp_file
File.open(‘public/’ + @path, “wb”) { |f|
f.write(@temp_file.read) }
end
end
def before_destroy
# delete the file from the filesystem
File.delete [‘public’,self.path]
end
private
def sanitize_filename(file_name)
# get only the filename, not the whole path (from IE)
just_filename = File.basename(file_name)
# replace all non-alphanumeric, underscore or periods with
underscores
just_filename.gsub(/[^\w.-]/,‘_’)
end
def set_path
self.path = ‘pictures/dog.png’
end
END
Thanks in advance for any help and thank you for such an amazing
framework!
Daniel H.