I am trying to create an upload form that allows the user to select a blank value which will then result in another upload process. ( I substituted in “class” for my actual class name).
My upload form is
<%= form_for @upload, :url => class_uploads_path(@uploader), :method =>
:post, :html =>{ :multipart => true } do |f| %>
<%= render "shared/error_messages", :target => @upload %>
<p>This media relates to...<br/>
<%= select "upload", "class_id", Class.all.collect {|class| [class.name,class.id] }, {
:include_blank => true } %></p>
<p>Title:<br/>
<%= f.text_field :title %></p>
<p>Description:<br/>
<%= f.text_area :description, :rows => 3 %></p>
<p>File to upload:<br/>
<%= f.file_field :data %></p>
<p><%= f.submit 'Upload for review' %></p>
<% end %>
Here is my create method, if the user leaves the select form blank I would like the first upload action to run and if they chose a class I want the second upload to run.
def create
upload_params = params[:upload] || params[:image] || params[:video]
@class = Class.find(upload_params[:class_id]) || nil
begin
if upload_params[:data]
file_name = upload_params[:data].original_filename
file_contents = upload_params[:data].read
end
rescue
@upload = Upload.new
flash[:error] = "Could not find upload file data. Please reselect file."
render :action => 'new' and return
end
begin
if @class.nil?
@upload = Upload.factory({ :file => file_contents,
:name => file_name,
:network => @uploader,
:title => upload_params[:title],
:description => upload_params[:description] })
else
@upload = Upload.factory({ :file => file_contents,
:name => file_name,
:class => @class,
:network => @uploader,
:title => upload_params[:title],
:description => upload_params[:description] })
end
@upload.save!
I have tried a number of different hacks, I am trying to avoid adding a new column to the database. Thanks in advance.
Kyle, if the blank option is chosen, I believe params[:class_id] should be “” (a blank string). You should check this — look in your development logs and see what params are getting passed back to your controller method, both when you select a class and when you don’t.
If that is correct:
As gg_s pointed out, there is lots of room for refactoring the code you posted. But if you just want to get the existing code working, this might be helpful.
In future, when something is not working, rather than just “hacking on it until it works”, look at the logs/console output for more information. Add logging statements to the controller method, printing out the values of variables, etc. Then try it out, and look at the logs again to see what is happening inside the method.