在Rails(6)应用程序(带有PG)中,我有一个Office
的{{1}}模型,它是room_ids
s的数组
UUID
使用不包含UUID的room_id创建办公室时,是否可以使用某种方式 t.uuid room_ids, array: true
*?
PG Error
应该引发这种错误。
但是现在
Office.create(room_ids: [1])
答案 0 :(得分:0)
您应该能够使用Postgres check constraints和适当的正则表达式。
这里有一篇博客文章,总结得很好:Rails Validations vs Postgres Check Constraints。从帖子中:
ALTER TABLE
users
ADD CONSTRAINT
users_name_must_look_like_a_name
CHECK (
name ~* '^.*[a-z] [a-z].*$'
);
尽管Rails并没有提供直接添加Postgres检查约束的方法,但是您可以在迁移中手动编写它们,可以看到in the Rails docs或in this SO answer的示例:
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