I’m trying to allow users to import a CSV file to an application’s database. I’ve been following the rails casts on importing csv and excel. I’m not sure how I can pass in a parameter that is not found in the excel or csv file.
For example I’m using devise for authentication and instead of the user having to input the user_id on the file being uploaded I want the user_id to be set to the current_user.id. How can I do this?
My code below:
Model’s method for importing the file
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Gear.create! row.to_hash
end
end
Controller Action
def import
Gear.import(params[:file])
redirect_to :back, notice: "Gears Uploaded"
end
One option is to just pass in the user ID into the
import-method like this:Model:
Controller:
Be aware that you will overwrite existing
user_id-columns in the CSV, but if I understand you correctly this is intended behavior.