为什么Rails无法自动生成.created_at?

时间:2018-12-10 20:35:32

标签: ruby-on-rails sqlite activerecord

我有一个由脚手架生成的模型,名为“ Pac”(政治行动委员会),带有时间戳。

我正在尝试从文本文件中获取有关pacs的数据。在我的seed.rb文件中,我解析文本文件以获得与我的ActiveRecord :: Pac类的属性相对应的数据哈希。此哈希称为“ pac_attributes”。

现在我尝试

Pac.find_or_create_by(pac_attributes)

,我收到以下错误消息:

SQLite3::ConstraintException: NOT NULL constraint failed: pacs.created_at

好吧,ActiveRecord :: Pac有时间戳,并且我的“ pac_attributes”哈希没有“ created_at”和“ updated_at”的显式条目,但是每次我以前使用过find_or_create_by时,这些字段都会自动生成(“ id”字段也是如此)。

发生了什么事?为什么“ find_or_create_by”失败并引发此错误?

应评论员的要求,我添加了以下信息:

schema.rb文件的摘录:

create_table "pacs", force: :cascade do |t|
  t.string "cycle"
  t.string "fec_id"
  t.string "pacshort"
  t.string "affiliate"
  t.string "ultorg"
  t.string "recipient_id"
  t.string "recipient_code"
  t.string "fec_candidate_id"
  t.string "party"
  t.string "prim_code"
  t.string "source"
  t.string "sensitive"
  t.boolean "foreign"
  t.integer "active"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

要获取“ pac_attributes”哈希,请执行以下操作:

pac_columns = Pac.column_names
pac_columns.delete_if { |x| x=='id' or x=='created_at' or x=='updated_at' }
puts pac_columns
pacs = File.join(Rails.root, 'app', 'assets', 'tables', 'cmtes18.txt' )
IO.foreach(pacs) do |line|
  line.chomp!("\r\n")
  pac_data = line.split(',')
  pac_data.each do |data|
    data.gsub!(/\|/,"")
    #The textfile is formatted with entries comma-separated and enclosed in '|' characters

  end
  pac_attributes = pac_columns.map(&:to_sym).zip(pac_data).to_h
  pac_attributes.delete_if{|_,v| v=="" }
  puts pac_attributes
  pac = Pac.find_or_create_by(pac_attributes)
end

“放入pac_attributes”返回:

{:cycle=>"2018", :fec_id=>"C00000018", :recipient_id=>"C00000018", :fec_candidate_id=>"H8TX22313", :foreign=>"0", :active=>"0"}

开发日志返回以下内容:

[1m[36mPac Load (0.1ms)[0m  [1m[34mSELECT  "pacs".* FROM "pacs" WHERE "pacs"."cycle" = ? AND "pacs"."fec_id" = ? AND "pacs"."recipient_id" = ? AND "pacs"."fec_candidate_id" = ? AND "pacs"."foreign" = ? AND "pacs"."active" = ? LIMIT ?[0m  [["cycle", "2018"], ["fec_id", "C00000018"], ["recipient_id", "C00000018"], ["fec_candidate_id", "H8TX22313"], ["foreign", "0"], ["active", 0], ["LIMIT", 1]]
[1m[35m (0.1ms)[0m  [1m[36mbegin transaction[0m
[1m[35mSQL (0.4ms)[0m  [1m[32mINSERT INTO "pacs" ("cycle", "fec_id", "recipient_id", "fec_candidate_id", "foreign", "active") VALUES (?, ?, ?, ?, ?, ?)[0m  [["cycle", "2018"], ["fec_id", "C00000018"], ["recipient_id", "C00000018"], ["fec_candidate_id", "H8TX22313"], ["foreign", "f"], ["active", 0]]
[1m[35m (0.0ms)[0m  [1m[31mrollback transaction[0m

0 个答案:

没有答案