#to_svelte

#to_svelte helps to streamline most-used attributes and labels from ActiveRecord to svelte:

ActiveRecord instance

@book.to_svelte(:title)
# => {
#        _schema: { 
#           ...
#       },
#        title: "..."
#    }

ActiveRecord Relation

@books.to_svelte(:title)
# => {
#        _schema: { 
#           ... 
#       },
#        data: [{ ... }]
#    }
  • Returns values in a array
  • Labels are always extracted, even if the relation does not contain a record

ActiveRecord Model

Book.to_svelte(:title)
# => {
#        _schema: { ... },
#    }
  • Only Schema is extracted.

Associations

Recursive: You can declare as many levels of association as you want.

@edition.to_svelte(
  book: [
    :name,
    {
      author: [
        :name
      ]
    }
  ]
)

Example Output

{
  "_schema" => {
    "self" => {
      "name" => "Buch",
      "namePlural" => "Bücher"
    },
    "name" => {
      "label" => "Name",
      "required" => true,
      "dbType" => :string,
      "dbDefaultValue" => nil
    },
    "isbnNumber" => {
      "label" => "ISBN-Nummer",
      "required" => false,
      "dbType" => :string,
      "dbDefaultValue" => "12345-default"
    }
  },
  "book" => {
    "name" => "Rails Cookbook",
    "isbnNumber" => "12345"
  },
  "date" => "2021-01-01"
}

Global Translations

Global translations can be configured that are always transferred to the output. Check: configuration/global_translations

Reserved Keys

The keys offset and limit are reserved for pagination control within associations. If your model has columns named offset or limit, they will be ignored to avoid conflicts.

Pagination Options

When querying associations, you can use the following options:

  • offset: Skips the specified number of records (e.g., offset: 2).
  • limit: Restricts the number of records returned (e.g., limit: 1).

Caching

The #to_svelte extracts:

  • Schema
    • watch_changes = false cached, recalculated after restarting the app on first request (for each language!)
    • watch_changes = true (usually on development/testing) recalculated on every request
  • Values
    • loaded on every request

Copyright © 2025-2027 sedlmair.ch. Distributed by MIT license.