【问题标题】:SQLite3::ConstraintException: NOT NULL constraint failed: items.title: INSERT INTO "items" ("image", "created_at", "updated_at") VALUES (?, ?, ?)SQLite3::ConstraintException: NOT NULL 约束失败:items.title: INSERT INTO "items" ("image", "created_at", "updated_at") VALUES (?, ?, ?)
【发布时间】:2019-12-25 06:38:24
【问题描述】:

我正在开发一个简单的应用程序,用户可以在其中将主题添加到购物车。但是有一个关于非空约束的错误。

浏览器显示的错误信息是这样的。

SQLite3::ConstraintException: NOT NULL 约束失败:items.title: INSERT INTO "items" ("image", "created_at", "updated_at") VALUES (?, ?, ?)

我已尝试删除schema.rb 中的非空约束。但是错误信息仍然存在。那么,我该怎么办?

架构:

create_table "items", force: :cascade do |t|
    t.string "image", null: false
    t.string "title", null: false
    t.string "description", null: false
    t.string "stock", null: false
    t.string "price", null: false
    t.integer "status", limit: 1, default: 0, null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

控制器:

class SellController < ApplicationController
  def new
    @item = Item.new
  end

  def confirm
  @item = Item.new(title: params[:title],price: params[:price],stock: params[:stock],description: params[:description],image: "default_item.jpg")
  render :new if @item.invalid?
  end

  def create
    @item = Item.new(title: params[:title],price: params[:price],stock: params[:stock],description: params[:description],image: "default_item.jpg")
    #@item = Item.new(item_params)
    if params[:image]
      @item.image = "#{@item.id}.jpg" 
      image = params[:image]
      File.binwrite("public/item_images/#{@item.image}", image.read)
    end
    if params[:back]
      format.html { render :new }
    elsif @item.save
      flash[:notice] = "your item data is saved."
      redirect_to("/sell/complete")
    else
      render("sell/new")
    end
  end

  def complete
  end
end

我希望保存项目数据并将浏览器上的页面更改为感谢页面。

【问题讨论】:

  • 尝试填写您的日期时间,created_at & updated_at

标签: ruby-on-rails ruby sqlite null ruby-on-rails-5


【解决方案1】:

仔细查看您的错误消息:

SQLite3::ConstraintException: NOT NULL 约束失败:items.title: INSERT INTO "items" ("image", "created_at", "updated_at") VALUES (?, ?, ?)

它表示items.title 列上的非空约束失败。实际上,您没有在插入语句中提供title。这意味着它们没有在您的控制器代码中传递给Item.new

我可以看到两个解决方案 - 如果您想保留所有这些约束(您的表中有多个非空列),您还应该添加活动记录 presence 验证。如果缺少值,它们将阻止向数据库调用insert 语句,并且它们会在@item.error 中为您提供很好的错误消息。

如果您可以允许这些列可以为空,则可以在迁移中删除约束:

change_column_null :items, :title, false

您还可以回滚创建items 表的迁移并编辑此迁移以避免在那里设置NOT NULL 约束。

schema.rb 在您运行迁移时生成,可用于将架构加载到数据库中。但它不会自动完成,您需要运行适当的 rake 任务 (rake db:schema:load)。不建议手动编辑此文件,因为它是自动生成的,您的更改将被自动覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 2018-06-10
    • 2021-08-07
    相关资源
    最近更新 更多