【发布时间】: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