Rails allow null when should not allow

Rails allowing null when should not allow

提问人:Diogo Amaral 提问时间:11/16/2023 最后编辑:tadmanDiogo Amaral 更新时间:11/16/2023 访问量:36

问:

class CreateProducts < ActiveRecord::Migration[7.0]
  def change
    create_table :products do |t|
      t.string :name
      t.string :code
      t.integer :gtin
      t.references :supplier, null: false, foreign_key: true
      t.references :group, null: false, foreign_key: true

      t.timestamps
    end
  end
end

当我创建表产品时,创建了上述迁移。但是我不想命名,代码应该接受null。因此,我创建了一个新的迁移,如下所示:

class ChangeNameAndCodeToNotNullInProducts < ActiveRecord::Migration[7.0]
  def change
    change_column :products, :name, :string, null: false
    change_column :products, :code, :string, null: false
  end
end

但是当我进入产品表单并单击创建时。它仍然接受创建所有数据为空白。我错过了什么?

Ruby-on-Rails 红宝石

评论

4赞 dbugger 11/16/2023
空字符串不是空字符串 -- 您的数据库在这些列中有空字符串的可能性很大。如果您使用的是 Rails 7.1 版本,请查看 atrribute 规范化器 github.com/mdeering/attribute_normalizer<
0赞 David Wolff 11/16/2023
如果您使用的是MySQL数据库,则也可能禁用了严格模式。查看 dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sql-mode-strict
1赞 tadman 11/16/2023
如果要将空字符串视为 null,请使用 to 将它们减少到保存之前。.presencenil
0赞 tonystrawberry 11/16/2023
您是否通过 Rails 控制台或数据库客户端检查了数据库中保存的实际值是多少?

答:

0赞 luisiniguezh 11/16/2023 #1

这种情况发生在我身上一次,您应该在应用迁移后重新启动 rails 服务器和/或控制台,之后它应该遵循 not null