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

时间:2017-07-03 16:16:03

标签: ruby-on-rails activerecord

在此表中:

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限制没有强制执行?

1 个答案:

答案 0 :(得分:2)

我刚刚对此进行了测试,并且数据库验证工作正常,但是使用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

的更多信息