I am following an example for how to upload a file from the great book Agile
Web Development with Rails (p 541-543, to be exact); however, instead of an
image file, I need to upload a csv file containing data that will get parsed
and stored in the database.
I believe I am following the example almost exactly, but for some reason, my
accessor method in my model that does the file parsing, is not firing?
Here's the code:
in my view:
<% form_tag (:action=> 'create', :multipart => true) do %>
<%= file_field_tag 'uploaded_file', :size=>50 %>
<p>
<%= submit_tag "Upload" %>
</p>
<% end %>
in my controller:
def create
@upload = Upload.new(params[:id])
respond_to do |format|
if @upload.save
flash[:notice] = 'Upload was successful.'
format.html { redirect_to(@upload) }
format.xml { render :xml => @upload, :status => :created, :location
=> @upload }
else
format.html { render :action => "new" }
format.xml { render :xml => @upload.errors, :status =>
:unprocessable_entity }
end
end
end
and in my model:
def uploaded_file=(file_field)
self.filename = base_part_of(file_field.original_filename)
# is here is where the uploaded file can be parsed?
FasterCSV.foreach(file.path,:headers=>"first_row", :col_sep=>"\t") do
|row|
row.each{|row| puts "row: #{row.inspect}"}
end
end
Following the example from the book, the "magic" part is the fact that the
file is uploaded in an attribute called uploaded_file, but there is no
database table that contains such a column. Instead, by naming an accessor
method in the model with the same name, it will receive the uploaded file.
However, when I submit a file, I just get the following error:
*
ActiveRecord::StatementInvalid in UploadsController#create *
PGError: ERROR: null value in column "filename" violates not-null constraint
which seems to indicate that the @upload.save is firing without the accessor
method having obtained the filename for it to be populated when the
upload object gets saved. But why would the book example work, and not in my
case?
I would extremely grateful if anyone can point out to me the error my ways!
thanks,
rixter
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.