Reputation: 1621
I am trying to import a csv file. I have the file loading but cant get the file to load the cell data into the model.
Here is my model with the import method. It should make an instance for each row and fill that instance with the attributes from each row. I see it importing the fie but not filling in any of the data from each row.
class Report < ActiveRecord::Base attr_accessor :contract,:start_time, :end_time, :source, :price require 'csv' def self.import(file) CSV.foreach(file.path, headers: true) do |row| report_hash = row.to_hash # exclude the price field report = Report.where(id: report_hash["id"]) if report.count == 1 report.first.update_attributes(report_hash) else Report.create!(report_hash) end end end
This is some of the cell content
contract,start_time,end_time,source,price
Corn,11-03-2014,11-16-2014,cme, 3.82
When I load the file i get this...
#<Report id: 380, created_at: "2016-02-04 03:41:50", updated_at: "2016-02-04 03:41:50", contract: nil, source: nil, price: nil, start_time: nil, end_time: nil>
Everything is nil other than created_at and updated_at what am I doing wrong?
Upvotes: 0
Views: 68
Reputation: 156
Your problem is in the line
attr_accessor :contract,:start_time, :end_time, :source, :price
I believe this interfere with the magic that ActiveRecord generates and it seems to me that the attr_accessor
overwrites AR and makes setting any of the fields not possible.
Remove this line and your code will work!
Upvotes: 2