我的问题:创建语句后数据库中的空值,这似乎是合法的。 Ruby 只是忽略了我的数据值……这令人费解。
情况:我正在尝试使用 rake 任务导入 CSV 数据。这是我要填充的模型(使用 mysql),desc 公司:
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 和 operator_num 是我的 CSV 文件中一行数据的前两个数据字段。 这是 Rails 模型(该表由迁移定义):
class Companies < ActiveRecord::Base
has_many :facilities, dependent: :destroy
attr_accessor :company_name, :operator_num
end
这是任务的初始代码:
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....)
这里的目的是创建一个Company记录,然后获取它的id作为外键;但奇怪的是,尽管 create 语句中的数据是正确的,但 company_name 和 operator_num 的记录是用空值创建的。
为了排除故障,我在 Rails 控制台中复制了该行为:
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">
这太奇怪了:Ruby 填充了时间戳字段,但忽略了数据字段!谁能向我解释为什么会这样?
最佳答案
您应该删除定义 attr_accessor
的行:它会覆盖 db getter 和 setter 以支持虚拟属性
关于ruby-on-rails - 为什么此 create 语句会忽略用于填充数据库记录的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352106/