Schema
Application data models should inherit from Crecto::Model
The Crecto::Model
class imposes the inherited
which imports the correct schema modules and sets up class wide variables and constants used for keeping track of associations and field names.
Schema
Inside the data model is where the database schema is defined.
The schema macro takes one argument and an options tuple. The argument is the database table name. If your database table doesn’t have a primary key, you can pass an option to disable it: schema "users", primary_key: false do
Default fields
By default Crecto assumes your table has the following column names defined id
, created_at
, and updated_at
.
These can be easily overridden.
Fields
Database table fields are defined using the field
macro. The field macro takes 2 arguments, the column name as a Symbol and the column type, and an optional options tuple.
Field types
Int
Float
Bool
String
Time
Array, postgres only
Arrays can be queries using build-in postgres methods
Json, postgres only
Json
fields can be both postgres json
or jsonb
types. If jsonb
is used, those fields can be queried using build-in postgres methods.
Field options
Enum fields
Non-nillable attributes
If you with to access attributes of a model without having to check for nil
, in the case that you are using a NOT NULL
database constraint you can use the non-nillable attribute accessors.
CAUTION: Mis-use of this could lead to Nil reference runtime exceptions