0

In a Rails (6) app (with PG), I have the Office model with room_ids which is an array of UUIDs

  t.uuid room_ids, array: true

Is there a way to raise some kind of PG Error* when an office is created with room_ids containing other than UUIDs?

Office.create(room_ids: [1]) should raise such Error.

But now

Office.create(room_ids: [1])
=> #<Office id: "24e835df-aed9-4d48-8855-82670375c374", room_ids: [nil]>
  • I'm not looking for Active Record Validations
Sig
  • 5,476
  • 10
  • 49
  • 89

1 Answers1

0

You should be able to use Postgres check constraints and the appropriate regex.

Heres a blog post that sums it up nicely: Rails Validations vs Postgres Check Constraints. From the post:

ALTER TABLE 
  users 
ADD CONSTRAINT 
  users_name_must_look_like_a_name 
CHECK (
  name ~* '^.*[a-z] [a-z].*$'
);

Although Rails doesn't provide a direct way to add a Postgres check constraint, you can write them manually in a migration, which you can see examples of in the Rails docs or 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
calebkm
  • 1,013
  • 4
  • 17