【问题标题】:Rails, null value in column violates not-null constraintRails,列中的空值违反非空约束
【发布时间】:2017-02-18 08:38:58
【问题描述】:

在生产中,我有一个模型类别。当我尝试在网站中创建类别时,出现以下错误

ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR:  null value in column "name" violates not-null constraint

迁移看起来像这样

class CreateCategories < ActiveRecord::Migration
  def up
    create_table :categories do |t|
      t.references :supercategory,     index: true
      t.string :name

      t.timestamps null: false
    end
    Category.create_translation_table! name: :string
  end
  ....
end

还有架构

  create_table "categories", force: :cascade do |t|
    ...
    t.string   "name"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.string   "slug"
    t.index ["restaurant_id"], name: "index_categories_on_restaurant_id", using: :btree
    t.index ["slug"], name: "index_categories_on_slug", unique: true, using: :btree
    t.index ["supercategory_id"], name: "index_categories_on_supercategory_id", using: :btree
  end

任何想法可能导致错误?谢谢! 如果您需要更多代码,请询问。

编辑 发送的参数

参数:{"utf8"=>"✓", "authenticity_token"=>"no3uGNSYkgClG+y6y9Y=", "category"=>{"name"=>"Coffee", "age_restriction"=>"0", "available_all_day"=>"0", "supercategory_id"=>"", “头像”=>#, @original_filename="coffee.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"category[avatar]\"; filename=\"coffee.JPG\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"创建类别", "remotipart_submitted"=>"true", "X-Requested-With"=>"IFrame", "X-Http-Accept"=>"text/javascript, 应用程序/javascript,应用程序/ecmascript, 应用程序/x-ecmascript, /; q=0.01", "restaurant_id"=>"乞力马扎罗咖啡"}

编辑 我尝试从控制台创建一个类别,发现模型没有名称列。好像没有正确迁移。我再次删除、创建和迁移了数据库,但该列仍然没有出现。任何想法来自哪里?

【问题讨论】:

  • 您可以在控制器中添加断点并在保存之前检查新的Category 对象吗?
  • 我在生产中,错误只出现在那里。我添加了发送的参数。

标签: ruby-on-rails


【解决方案1】:

很难想象如果 PostgreSQL 表没有将该列设置为非空,你怎么会得到这个错误,所以我怀疑你没有使用你认为你正在使用的数据库。

您可以检查活动记录认为哪些列设置为不为空:

Category.columns.reject{|c| c.null}.map(&:name)

【讨论】:

  • 你的命令的输出是 => ["id", "created_at", "updated_at"]。我相信非空要求来自我验证的类别模型:名称,存在:真
  • 不过,这不会引发 ActiveRecord PG 错误。你会在#save 上得到一个错误!但是#save(最后没有爆炸)只会返回false。
  • 恐怕我没主意了。
猜你喜欢
  • 2021-11-02
  • 1970-01-01
  • 2016-02-14
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 2021-03-30
相关资源
最近更新 更多