如何在Rails迁移中添加检查约束? [英] How do I add a check constraint in a Rails migration?

查看:80
本文介绍了如何在Rails迁移中添加检查约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Rails应用程序中的现有表中添加一个新的整数列.该列只能具有值1、2、3,因此我想向表/列添加检查约束.如何在Rails迁移中指定此约束?

I need to add a new integer column to an existing table in my Rails app. The column can only have values 1, 2, 3, so I'd like to add a check constraint to the table/column. How do I specify this constraint within a Rails migration?

推荐答案

Rails迁移没有提供任何添加约束的方法,但是您仍然可以通过迁移来实现,但只需将实际的SQL传递给execute()

Rails migration does not provide any way to add Constraints, but you can still do it via migration but by passing actual SQL to execute()

创建迁移文件:

ruby script/generate Migration AddConstraint

现在,在迁移文件中:

class AddConstraint < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE table_name ADD CONSTRAINT check_constraint_name CHECK (check_column_name IN (1, 2, 3) )"
  end

  def self.down
    execute "ALTER TABLE table_name DROP CONSTRAINT check_constraint_name"
  end
end

这篇关于如何在Rails迁移中添加检查约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆