Skip to content

Add support for choices on string model and schema fields #393

Description

@ellmetha

Description

Let's add support for choices on string model and schema fields.

Rationale

Marten presently supports string fields for persisting and validating string values, and enum fields for restricting values to a Crystal Enum. However, there is no lightweight way to restrict a string field to a predefined set of values without defining a dedicated enum class.

To palliate this, let's introduce a choices option for string fields (similar to Django's choices), allowing allowed values to be specified inline at field definition time.

Usage

Model fields

class Article < Marten::Model
  field :id, :big_int, primary_key: true, auto: true
  field :status, :string, max_size: 20, choices: ["draft", "published", "archived"]
end

article = Article.new(status: "draft")
article.valid? # => true
article.status = "invalid"
article.valid? # => false

Schema fields

class ArticleSchema < Marten::Schema
  field :status, :string, choices: ["draft", "published", "archived"]
end

Restrictions

  • The choices option should only be available on string fields.
  • All choice values should respect the field's max_size constraint.
  • Invalid values should fail validation with a clear error message.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions