Hi everybody!
I’m new in programming Ruby on Rails, and I have a big problem with a
picture upload. I like to save thumbnails in the directory structure and
save the image name in the database.
So that’s what I’ve done:
new.html.erb
Untitled DocumentPost new Challenge
<%= form_tag({:action => :create}, {:multipart => true}) %>Challenge Title:
<%= text_field :challenge, :title%>Description:
<%= text_field :challenge, :description%>Challenge Thumbnail:
<%= file_field :challenge, :thumbnail%> <%= submit_tag 'create' %> <% if flash[:error]%><%= flash[:error]%>
challenges_controller.rb
def new
@challenge = Challenge.new
end
def create
@challenge = Challenge.new params[:challenge]
if [email protected]?
flash.now[:error] = 'Alles muss angegeben werden!'
render :action => 'new'
else if [email protected]_thumbnail
flash.now[:error] = 'Fehler beim hochladen des thumbnails!'
render :action => 'new'
else
@challenge.save
redirect_to(:action => :list)
end
end
end
challenge.rb
class Challenge < ActiveRecord::Base
belongs_to :user
IMAGE_DIR = ‘/images/upload’
THUMBNAIL_DIR = IMAGE_DIR + ‘/thumbnails’
def thumbnail= (thumbnail_field)
if thumbnail_field.size > 0
@thumbnail = thumbnail_field
self.thumbnail = thumbnail_field.original_filename
end
end
def save_thumbnail
if !save_uploaded_file(@thumbnail, THUMBNAIL_DIR,
self.thumbnail_file)
return false
end
end
def save_uploaded_file(fileobj, filepath, filename)
complete_path = RAILS_ROOT + ‘/public/’ + filepath
FileUtils.mkdir_p(complete_path) unless File.exists?(complete_path)
begin
filename = unique_and_proper_filename filename
f = File.open(complete_path + ‘/’ + filename, ‘wb’)
f.write(fileobj.read)
rescue
return false
ensure
f.close unless f.nil?
end
end
def unique_and_proper_filename(filename)
Time.now.to_i.to_s + ‘_’ + File.basename(filename)
end
end
I’m getting the error message: NoMethodError in
ChallengesController#create
undefined method `original_filename’ for “DSC00672.JPG”:String
I’ve tried everything, but I cant get it run correctly.
So please help!
Thanks, Manuel