Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override created_at field in model when importing a CSV?

I'm importing a CSV full of waitlist signups into my database with previous created dates, how can I import them while keeping their initial dates vs. having them all show the same date of importing?

I get the error: Rails can't mass-assign protected attributes for id, created_at

The code:

 csv_file = params[:csv][:file].read
    csv = CSV.parse(csv_file, :headers => false) 
    csv.each do |row|
       Model.create!(:email => row[0], :created_at => row[1])    
    end    
like image 294
patrick Avatar asked May 19 '12 22:05

patrick


2 Answers

In Rails 4:

attr_accessible is no longer used and including it a the top of a model will likely break your code. Merely including :created_at in the args passed to create! should do it.

Turning @Ghoti's comment into an answer here to give it more visibility

like image 69
Peter Berg Avatar answered Sep 27 '22 20:09

Peter Berg


You need to add the desired column to the attr_accessible

class Tutorial < ActiveRecord::Base
  attr_accessible :created_at
end
like image 39
rogeliog Avatar answered Sep 27 '22 21:09

rogeliog