#to_svelte
When interacting with Rails and Svelte components, you will mostly need the following:
- Data values or method results from a data model
- Translated model names (plural and singular)
- Translated attribute labels
- enum keys and tranlated labels
- … and maybe some more translations that you often need on your special app.
- It may also be useful to have some front-end helpers that interact with this data, such as the @csedl/hotwire-svelte-helpers > templates > FormInput.svelte
The
#to_sveltehelpers are designed exactly for this purpose.
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 = falsecached, 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