Skip to content

Commit

Permalink
Adding guides on using array enums. Fixes #1296
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink committed Jul 27, 2024
1 parent d4865ff commit e71337e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
31 changes: 31 additions & 0 deletions src/actions/guides/database/models.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)}).
Expand Down
11 changes: 10 additions & 1 deletion src/actions/guides/database/querying.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down

0 comments on commit e71337e

Please sign in to comment.