Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document default values for model columns #395

Merged
merged 2 commits into from
Aug 11, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/actions/guides/database/migrations.cr
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Guides::Database::Migrations < GuideAction
ANCHOR_ASSOCIATIONS = "perma-associations"
ANCHOR_PRIMARY_KEYS = "perma-primary-keys"
ANCHOR_ASSOCIATIONS = "perma-associations"
ANCHOR_PRIMARY_KEYS = "perma-primary-keys"
ANCHOR_ADVANCED_COLUMN_OPTIONS = "perma-advanced-column-options"
guide_route "/database/migrations"

def self.title
Expand Down Expand Up @@ -208,6 +209,7 @@ class Guides::Database::Migrations < GuideAction
* `JSON::Any` - Maps to postgres `jsonb`.
* `Array(T)` - Maps to postgres array fields where `T` is any of the other datatypes.

#{permalink(ANCHOR_ADVANCED_COLUMN_OPTIONS)}
### Advanced Options

The `add` method takes several options for further customization when adding a field.
Expand Down
19 changes: 19 additions & 0 deletions src/actions/guides/database/models.cr
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,25 @@ class Guides::Database::Models < GuideAction
end
```

### Setting a column default value

While you can always define database-level default values in a [migration](#{Guides::Database::Migrations.path(anchor: Guides::Database::Migrations::ANCHOR_ADVANCED_COLUMN_OPTIONS)}) or set default values in a SaveOperation, it's also possible to set a default value at the model level. For example:

```crystal
class User < BaseModel
table do
column email
column encrypted_password : String

column greeting : String = "Hello there!"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

General Kenobi

column admin : Bool = false
column money : Float64 = 0.0
end
end
```

This helps to avoid boilerplate application code, and instead allows your models to do the heavy lifting for you. It also provides one convenient source of truth for the business logic behind any given model.

#{permalink(ANCHOR_COLUMN_TYPES)}
### Column types

Expand Down