2017-07-03 44 views
3

在该表中:`长度:`没有在PostgreSQL的字符串列上强制执行?

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

什么运行时会发生'Peripheral.columns_hash ['label']。limit'在你的控制台? – jdgray

回答

2

我刚刚测试过这个和数据库验证工作,但它的良好做法与轨道上的红宝石删除此验证,并将其移入模型。 从模型,这成为更容易找到和更新,以及你有其他一系列的东西,你可以做的比其他只检查一个最大

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