【问题标题】:Rails Custom Primary Key: SQLite3::ConstraintException: NOT NULL constraint failedRails 自定义主键:SQLite3::ConstraintException:NOT NULL 约束失败
【发布时间】:2020-06-01 00:43:26
【问题描述】:

我的 Products 表中有一个自定义主键 (PK) ASIN。这个 PK 是一个字符串。

  def change
    create_table :products, id: false do |t|
      t.references :user, null: false, foreign_key: true
      t.primary_key :asin
      t.string :image
      t.string :price
      t.string :title

      t.timestamps
    end
      change_column :products, :asin, :string
  end

在我的产品模型中,我有以下内容:

  self.primary_key = 'asin'
  belongs_to :user

  validates_uniqueness_of :asin
  validates_presence_of :asin, :image, :title, :price, :user_id

  before_save :before_save

  def before_save
    self.asin  = self.asin.upcase!
  end

我已多次查看代码,但在尝试点击此路线并创建产品时,这是我收到的错误。

"exception": "#<ActiveRecord::NotNullViolation: SQLite3::ConstraintException: NOT NULL constraint failed: products.asin>"

这是我发送到这个创建路由的 JSON

{
    "asin": "B",
    "title": "Test",
    "image": "test",
    "user_id": 1,
    "price": "test"
}

注意:我知道在这个庄园中使用 PK 通常会被忽视,请知道我承认这一点,但这是我项目目标的理想设置。请不要离开卑鄙的cmets。

编辑:作为参考,这里是 Products 控制器下的 Create 函数。

  skip_before_action :authorize_request, only: [:create, :show]

  def create
    Product.create!(product_params)
    json_response(product_params, :created)
  end

  def product_params
    params.permit(
        :asin,
        :image,
        :title,
        :user_id,
        :price
    )
  end

【问题讨论】:

  • 在尝试插入新记录时 Rails 抛出的整个错误是什么?
  • @SebastianPalma 在 92 毫秒内完成了 500 个内部服务器错误(ActiveRecord:13.1 毫秒 | 分配:14739) ActiveRecord::NotNullViolation(SQLite3::ConstraintException:NOT NULL 约束失败:products.asin):app/controllers /products_controller.rb:16:in `create'
  • 作为参考,添加了一个在 Products 控制器下显示 Create 函数的编辑。

标签: sql ruby-on-rails sqlite


【解决方案1】:

编辑:部分问题是 asin 的第一个字母在发送到后端之前需要小写。

我不完全确定这里发生了什么来解决这个问题。但是我运行以下命令只是为了测试,因为我确信这个数据库设置非常好。

首先,我在 mac 上使用 control + c 停止了服务器。

我使用 rails c 连接到 Rails 我使用Product.connection 连接到产品表 我创建了一个测试产品只是为了看看有什么问题Product.create!(asin: "Test_ASIN", title: "title", image: "image", price: "price", user_id: 1)

我很惊讶地发现这行得通,因为这正是我最初发送到后端的内容,但随后我继续启动 rails s 并尝试再次发送请求,这一次,它提交了。

我希望这对那里的人有所帮助,因为这太奇怪了。

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 2013-03-04
    • 1970-01-01
    • 2022-08-10
    • 2021-08-07
    • 2015-12-31
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多