views:

54

answers:

1

I'm having an extremely frustrating time getting some images to upload. They are obviously being uploaded as rack/multipart but the way that I'm iterating over my params hash must be causing the problem. I could REALLY use some help, so I can stop pulling out my hair.

So I've got a params hash that looks like this:

Parameters: {"commit"=>"Submit", "sighting_report"=>[{"number_seen"=>"1", "picture"=>#<File:/var/folders/IX/IXXrbzpCHkq68OuyY-yoI++++TI/-Tmp-/RackMultipart.85991.5>, "species_id"=>"2"}], "authenticity_token"=>"u0eN5MAfvGWtfEzrqBt4qfrL54VJ9SGX0jFLZCJ8iRM=", "sighting"=>{"sighting_date(2i)"=>"6", "name"=>"", "sighting_date(3i)"=>"5", "county"=>"0", "notes"=>"", "location"=>"", "sighting_date(1i)"=>"2010", "email"=>""}}

My form can have multiple sighting reports with multiple pictures in each sighting report. Here's my controller code:

def create_multiple
    @report = Report.new
    @report.name = params[:sighting]["name"]
    @report.sighting_date = Date.civil(params[:sighting][:"sighting_date(1i)"].to_i, params[:sighting][:"sighting_date(2i)"].to_i, params[:sighting][:"sighting_date(3i)"].to_i)
    @report.county_id = params[:sighting][:county]
    @report.location = params[:sighting][:location]
    @report.notes = params[:sighting][:notes]
    @report.email = params[:sighting][:email]
    @report.save!
    @report.reload
    for sr in params[:sighting_report] do
        sighting = SightingReport.new
        sighting.report_id = @report.id
        sighting.species_id = sr[:species_id]
        sighting.number_seen = sr[:number_seen]
        sighting.save
        if sr[:picture]
            sighting.reload
            for pic in sr[:picture] do
                p = SpeciesPic.new
                p.uploaded_picture = pic
                p.species_id = sighting.species_id
                p.report_id = @report.id
                p.save!
            end
        end
    end
    redirect_to :action => 'new_multiple'
end

I can't seem to access the picture data itself, but keep getting access to some string. It's not the file name though, some strange thing with escaped characters. What can I do to access the actual data?

A: 

You should be using accepts_nested_attributes_for (as described here: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

This will remove all of the complexity from the controller and allow some Rails magic to handle nested object creation. This will also perform all of the saves as one atomic transaction.

Patrick Klingemann