Ash FrameworkAF
Ash Framework6mo ago
3 replies
Shahryar

Best way to consist between attributes validation and Postgres level

Hi, sorry, I just try to learn and compare my code with the best ways that i can be able to find.
I just want to know, is there auto way to create constraints?
For example based on attributes constraints? or it should be written by manual check_constraints ?

attributes do
    uuid_primary_key :id

    attribute :name, :string do
      allow_nil? false
      public? true
      constraints min_length: 3, max_length: 70, trim?: true

      description "Human-readable site name"
    end

    attribute :host, :string do
      allow_nil? false
      public? true
      constraints min_length: 3, max_length: 200, trim?: true
      description "Domain name for the site (e.g., example.com)"
    end

    attribute :priority, :integer do
      default 0
      public? true
      constraints min: 0, max: 100
      description "Priority for site routing (higher = more priority)"
    end

    attribute :active, :boolean do
      default true
      public? true
      description "Whether the site is currently active"
    end

    create_timestamp :inserted_at
    update_timestamp :updated_at
  end


And my constraints is (for example delete this part)

   check_constraints do
      check_constraint :name, "name_length_check", 
        check: "length(name) >= 3 AND length(name) <= 70",
        message: "Name must be between 3 and 70 characters"

      check_constraint :host, "host_length_check", 
        check: "length(host) >= 3 AND length(host) <= 200", 
        message: "Host must be between 3 and 200 characters"

      check_constraint :priority, "priority_range_check",
        check: "priority >= 0 AND priority <= 100",
        message: "Priority must be between 0 and 100"

      # Multiple attributes can share the same constraint
      check_constraint [:name, :host], "no_empty_strings",
        check: "name != '' AND host != ''",
        message: "Name and host cannot be empty"
    end


Thank you in advance
Solution
It needs to be written manually with check constraints as you have done it. We may add that feature in the future
Was this page helpful?