ajk4550
ajk4550

Reputation: 741

Appending to a file read in rails

I want to be able to upload a CSV of recipients for an event mailing. I've got the upload portion working and my application is saving the data to a database, however, I need to add two fields that I don't expect the user to know.

    csv_text = File.read(params[:file].path)
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
        Recipient.create!(row.to_hash)
    end

I want to add the :event_id and the :mailing_id and I don't expect the user to know this so I don't expect them to put it in the CSV when they upload. Those details are being passed with the request:

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"QvKQeTVQb1UJJHh4ulkF8T0r24QrpIuMPP4NXFOYJhM=",
 "file"=>#<ActionDispatch::Http::UploadedFile:0x007fbd4137fdb0 @tempfile=#<Tempfile:/var/folders/js/39l33x3d2vd06c_v7hbymtw474d6cc/T/RackMultipart20150814-15094-11f1q3v>,
 @original_filename="import_test.csv",
 @content_type="text/csv",
 @headers="Content-Disposition: form-data; name=\"file\"; filename=\"import_test.csv\"\r\nContent-Type: text/csv\r\n">,
 "commit"=>"Save changes",
 "event_id"=>"1",
 "mailing_id"=>"1"}

How can I make sure these two fields are included when I insert the user into the database?

Upvotes: 0

Views: 70

Answers (1)

Francesco Belladonna
Francesco Belladonna

Reputation: 11689

What about the following:

csv_text = File.read(params[:file].path)
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
    Recipient.create!(row.to_hash.merge(mailing_id: params[:mailing_id].to_i, event_id: params[:event_id].to_i)
end

Upvotes: 3

Related Questions