ActiveRecord::NotNullViolation:运行时错误:NOT NULL 约束失败:drives.created_at

问题描述 投票:0回答:1

我正在使用最新的 ruby 3.3.3 和最新的 Rails 7.1.3.4。

我是 Rails 新手,我正在学习它。抱歉,如果我的要求对某些人来说似乎很愚蠢。

我在运行测试时遇到此错误。

ActiveRecord 似乎无法用

Time.now
预填充它们。根据文档here,应该这样做。

我尝试在全新安装中重现该问题,但效果很好。我不明白我的项目出了什么问题,尤其是几乎相同的代码。

这是我的模型的样子:

class Drive < ApplicationRecord
  with_options presence: true do
    validates :name
    validates :provider
    validates :credentials
  end

  encrypts :credentials
end

迁移文件:

class CreateDrives < ActiveRecord::Migration[7.1]
  def change
    create_table :drives do |t|
      t.string :name
      t.string :provider
      t.text :credentials

      t.timestamps
    end
  end
end

赛程:

# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html

one:
  name: MyString
  provider: MyString
  credentials: MyText

two:
  name: MyString
  provider: MyString
  credentials: MyText

查看 test.log 时,我发现这些条目:

  [1m[36mTRANSACTION (0.0ms)[0m  [1m[36mbegin transaction[0m
  [1m[36mFixtures Load (0.2ms)[0m  [1m[31mDELETE FROM "drives";
INSERT INTO "drives" ("name", "provider", "credentials") VALUES ('MyString', 'MyString', 'MyText');
INSERT INTO "drives" ("name", "provider", "credentials") VALUES ('MyString', 'MyString', 'MyText')[0m
  [1m[36mTRANSACTION (0.0ms)[0m  [1m[31mrollback transaction[0m

我找不到问题所在并修复它。非常感谢帮助

ruby-on-rails ruby testing activerecord ruby-on-rails-7
1个回答
0
投票

您需要在灯具中设置

updated_at
created_at
值(这些是由迁移文件中的
t.timestamps
语句创建的列):

one:
  name: MyString
  provider: MyString
  credentials: MyText
  created_at: <%= Time.now %>
  updated_at: <%= Time.now %>

two:
  name: MyString
  provider: MyString
  credentials: MyText
  created_at: <%= Time.now %>
  updated_at: <%= Time.now %>
© www.soinside.com 2019 - 2024. All rights reserved.