【问题标题】:Is 'Archive' a reserved word in Rails or SQLite3?“存档”是 Rails 或 SQLite3 中的保留字吗?
【发布时间】:2019-08-23 12:00:07
【问题描述】:

迁移名为“存档”的模型后,所有测试都失败并显示 ActiveRecord / 错误消息,如下所示:

ActiveRecord::NotNullViolation: SQLite3::ConstraintException: NOT NULL constraint failed: archives.created_at: INSERT INTO "archives" ("some_thing") VALUES ('MyString')

这是在运行全新安装的 Ubuntu 18.04.2 和 Ruby 2.6.1 和 Rails 5.2.3 的新 VM 上的新 Rails 应用程序中隔离的,遵循 Odin 项目的安装说明。该问题仅在名为“存档”的模型的测试期间出现,并且删除模型的属性只会将错误更改为:

ActiveRecord::StatementInvalid: SQLite3::SQLException: incomplete input: INSERT INTO "archives"

我的工作流程如下:

rails new sample_app

cd sample_app

(在撰写本文时将 Gemfile 中的 sqlite3 更改为使用版本 '~> 1.3.6' 来修复错误)

bundle install

rails g model Archive

生成此迁移:

class CreateArchives < ActiveRecord::Migration[5.2]
  def change
    create_table :archives do |t|

      t.timestamps
    end
  end
end
rails db:migrate

创建此架构:

ActiveRecord::Schema.define(version: 2019_04_03_003144) do

  create_table "archives", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end
rails db:test

运行此测试:(未注释)

require 'test_helper'

class ArchiveTest < ActiveSupport::TestCase
  test "the truth" do
    assert true
  end
end

运行测试后,通常是给定的通过,Rails 返回上面列出的第一条 ActiveRecord 错误消息。 我觉得我在这里遗漏了一些东西,使我无法对模型使用“存档”这个词。

【问题讨论】:

  • 也分享给你 schema.rb,专门用于“存档”和你的测试文件
  • 刚刚在问题中添加了架构、迁移和模型测试。
  • 根据this list,看起来'archive'可能是Rails中的保留字。

标签: ruby-on-rails activerecord sqlite


【解决方案1】:

Archive 不是保留字。您提供的链接在过去 5 年内未更新。

这背后的原因是:

您正在创建存档记录,但未提供created_atupdated_at,根据您的schema,它们是必填字段。

t.datetime "created_at", null: false
t.datetime "updated_at", null: false

解决方案:

要么更改您的迁移以允许将 null 插入到 created_atupdated_at 中,要么转到您的 test/fixtures/archive.yml 并在那里提供 created_atupdated_at

喜欢:

one:
  ....some fields....
  created_at: 2018-08-30 14:41:23
  updated_at: 2018-08-30 14:41:23

更新

现在第二个问题是因为您没有除timestamp 以外的任何字段。删除此表并为至少 1 个字段的存档创建新模型。目前 Rails 正在生成查询 INSERT INTO "Archives"; 并且 SQL 需要此查询之后的数据,这就是它向您返回错误的原因。

【讨论】:

  • 这实际上解决了测试问题,但是这仍然存在仅在此处名称为“存档”的模型上发生的谜团。另一个名称的模型夹具,即“存档”,将默认自动生成这两列。
  • 另一件事:从迁移中删除时间戳,或将它们设置为 allow null 会导致上面列出的第二个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多