Rails - DB级别验证':start_date '和':end_date '



我有一个关于Rails中以下代码的问题:

class CreateEmployments < ActiveRecord::Migration[6.0]
def change
create_table :employments do |t|
t.string :title, null: false
t.string :company_name
t.datetime :start_date
t.datetime :end_date
t.integer :user_id
t.timestamps
end
end
end

我试图禁止数据库接受任何大于:end_date的:start_date值。我希望:end_date总是大于:start_date,并希望在db级别这样做。有办法吗?我知道我可以使用模型字段验证,但我也想在数据库级别实现它。任何建议吗?提前感谢!

DB级别的规则称为约束。

class AddEmploymentsDateConstraint < ActiveRecord::Migration
def self.up
execute "ALTER TABLE employments ADD CONSTRAINT employments_date_check CHECK (end_date > start_date)"
end
def self.down
execute "ALTER TABLE employments DROP CONSTRAINT employments_date_check"
end
end

知道使用了什么DB是很重要的。例如,如果使用SQLite,不能使用ALTER TABLE语法添加约束-只有在CREATE TABLE上才能添加约束。看到答案。

另外,rails 6.1+支持约束,参见另一个答案。

相关内容

最新更新