From e71337e6ca640692e194cc43487e40ab11d897bc Mon Sep 17 00:00:00 2001 From: Jeremy Woertink Date: Sat, 27 Jul 2024 14:36:42 -0700 Subject: [PATCH] Adding guides on using array enums. Fixes #1296 --- src/actions/guides/database/models.cr | 31 +++++++++++++++++++++++++ src/actions/guides/database/querying.cr | 11 ++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/actions/guides/database/models.cr b/src/actions/guides/database/models.cr index 71e79b2e..c45ad15a 100644 --- a/src/actions/guides/database/models.cr +++ b/src/actions/guides/database/models.cr @@ -376,6 +376,37 @@ class Guides::Database::Models < GuideAction end ``` + ### Array Enums + + For `Array(SomeEnum)` columns, you will store these on the postgres side as array of ints. Then on the model side, you must + use the `PG::EnumArrayConverter` custom converter. + + ```crystal + # Use this for your migrations + create table_for(Post) do + primary_key id : Int64 + + add reactions : Array(Int32), default: [] of Int32 + end + ``` + + ```crystal + # src/models/post.cr + class Post < BaseModel + + enum Reaction + Like + Love + Funny + Shocked + end + + table do + column reactions : Array(Reaction) = [] of Post::Reaction, converter: PG::EnumArrayConverter(Post::Reaction) + end + end + ``` + To learn more about using enums, read up on [saving with enums](#{Guides::Database::SavingRecords.path(anchor: Guides::Database::SavingRecords::ANCHOR_SAVING_ENUMS)}) and [querying with enums](#{Guides::Database::Querying.path(anchor: Guides::Database::Querying::ANCHOR_QUERYING_ENUMS)}). diff --git a/src/actions/guides/database/querying.cr b/src/actions/guides/database/querying.cr index 840e7608..48f88bd7 100644 --- a/src/actions/guides/database/querying.cr +++ b/src/actions/guides/database/querying.cr @@ -401,12 +401,21 @@ class Guides::Database::Querying < GuideAction Admin end - #... + enum Color + Red + Blue + Green + Yellow + end + + column role : User::Role + column colors : Array(User::Color) end ``` ```crystal UserQuery.new.role(User::Role::Admin) + UserQuery.new.colors.includes(User::Color::Green) ``` ### Any? / None?