My problem: null values in the database after a create statement, which seems otherwise legitimate. Ruby is simply ignoring my data values...which is baffling.
The situation: I am trying to import CSV data using a rake task. Here is the model I am trying to populate (using mysql), desc companies:
mysql> describe companies;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| company_name | varchar(100) | YES | | NULL | |
| operator_num | int(11) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
Company_name and operator_num are the first two data fields in a row of data in my CSV file. Here is the Rails model for this (the table was defined by a migration):
class Companies < ActiveRecord::Base
has_many :facilities, dependent: :destroy
attr_accessor :company_name, :operator_num
end
Here is this initial code for the task:
desc "Imports the CSV file into database"
task :import_cogcc => :environment do
require 'csv'
CSV.foreach('public/partial.csv', :headers => true) do |row|
# create records in independent tables
# create the Company object
this_company_name = row['name'].strip!
this_operator_num = row['operator_num']
if !(Companies.exists?(:company_name => this_company_name))
Companies.create(company_name: this_company_name, operator_num: this_operator_num)
end
thecompany = Companies.find(:first, :conditions => ["this_company_name = ?", this_company_name])
company_id = thecompany.id
# create the County object
(code continues from here....)
The purpose here is to create a Company record, then get the id for it to use as a foreign key; but the wierd thing is, the record gets created with null values for company_name and operator_num, despite the data is correct in the create statement.
Trying to troubleshoot, I replicated the behavior in the rails console:
irb(main):002:0> this_operator_num = 195
=> 195
irb(main):003:0> this_company_name = "44 CANYON LLC"
=> "44 CANYON LLC"
irb(main):004:0> Companies.create(company_name: this_company_name, operator_num: this_operator_num)
(0.1ms) BEGIN
SQL (0.5ms) INSERT INTO `companies` (`created_at`, `updated_at`) VALUES ('2014-08-17 17:48:01', '2014-08-17 17:48:01')
(23.5ms) COMMIT
=> #<Companies id: 2, company_name: nil, operator_num: nil, created_at: "2014-08-17 17:48:01", updated_at: "2014-08-17 17:48:01">
This is just too bizarre: Ruby populates the timestamp fields, but ignores the data fields! Can anyone explain to me why this happens?
Company) for the table,companies.