gpt4 book ai didi

ruby-on-rails - `length:` 没有在 PostgreSQL 的字符串列上强制执行?

转载 作者:行者123 更新时间:2023-12-04 03:41:56 25 4
gpt4 key购买 nike

在这张表中:

create_table "peripherals", id: :serial, force: :cascade do |t|
t.string "label", limit: 280
end

我将 label 字段限制为 280 个字符。我使用 PostgreSQL 作为我的数据库。

即使超过 280 个字符,此记录也会保存到数据库中,不会引发任何异常:

Peripheral.create!(label:  ("X" * 700))

为什么我的 280 限制没有强制执行?

最佳答案

我刚刚对此进行了测试,数据库验证有效,但是使用 ruby​​ on rails 删除此验证并将其移至模型中的良好做法。从模型中,这变得更容易找到和更新,除了检查最大值之外,您还可以做一系列其他事情

class Peripheral < ApplicationRecord
validates_length_of :label, :maximum => 280 # there shouls be no more than 280 characters
#validates_length_of :label, :minimum => 2 # there shouls be no less than 2 characters
#validates_length_of :label, :in => 2..280 # the number of character should be between 2 and 280
#validates_length_of :label, :is => 280 # The number of character should be exacly 280
end

您可以找到更多关于 validates-length-of 的信息

关于ruby-on-rails - `length:` 没有在 PostgreSQL 的字符串列上强制执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44890107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com