Using form_tag with a bit of rails 'magic'?

I’m trying to follow an example from ‘Agile Web D. with Rails’
(3rd
ed) which shows how to upload an image file, except that I’m trying to
upload a csv file.

The ‘magic’ that the example shows is how the file_field helper method
can
say “file_field(“uploaded_file”)” when there is actually no
“uploaded_file”
column in the upload table, because the following method can be put in
the
model:

def uploaded_file=(upload_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

def base_part_of(file_name)
File.basename(file_name)
end

However, this method never seems to fire. Instead, when I upload the
file, I
get the error:

    ERROR:  null value in column "filename" violates not-null 

constraint

which, of course, would happen if a record is inserted without assigning
the filename to the upload object.

My code is shown below; would appreciate if anyone can tell me why my
uploaded_file method is not firing:

My model:
<% form_tag (:action=> ‘create’, :multipart => true) do %>
<%= file_field_tag ‘uploaded_file’ %>

<%= submit_tag "Upload" %>

<% end %>

My controller:
def create
@upload = Upload.new(params[:upload])

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

My model:
require ‘fastercsv’

def new
@upload = Upload.new
end

def uploaded_file=(upload_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

def base_part_of(file_name)
File.basename(file_name)
end

Your setter needs to be same name as the field that rails is looking
for.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs