找到你要的答案

Q:Appending to a file read in rails

Q:追加到一个文件中读取钢轨

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?

我希望能够上传事件邮寄CSV的收件人。我已经得到了上传部分的工作,我的应用程序是保存数据到数据库,但是,我需要添加两个领域,我不希望用户知道。

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

我想补充的:event_id和:mailing_id我不指望用户知道这个所以我不希望他们把它当他们上传的CSV。这些细节正在通过请求:

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"}

如何将这两个字段包含在将用户插入数据库中时?

answer1: 回答1:

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

下面怎么办:

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
ruby-on-rails  ruby  csv  ruby-on-rails-4