Clear ORM
Search…
Defining your model
Model definition in Clear is done by inclusion of the Clear::Model module in your class. Assuming we have this table in PostgreSQL:
1
CREATE TABLE articles (
2
id serial NOT NULL PRIMARY KEY,
3
name text NOT NULL,
4
description text
5
);
Copied!
The definition of this model is straight forward:
article.cr
1
class Article
2
include Clear::Model
3
4
column name : String
5
column description : String?
6
7
column id : Int32, primary: true, presence: false
8
end
Copied!
Cut step by step, this is what happens:
First, we include all the magic of Clear in our class:
1
include Clear::Model
Copied!
Second, we define name column as String. Clear will map automatically the column to the model attribute.
1
column name : String
Copied!
Third, we define description . We defined descriptionas NULLABLE in our database. To reflect this choice, we add Nilable ? operator to our column.
1
column description : String?
Copied!
Finally, we define id as our primary key for this model. While being declared as NOT NULL, the column is defined with a default value in PostgreSQL. Therefore, we tell Clear to not check value presence on save/validate by adding presence: false to the column definition.
1
column id : Int32, primary: true, presence: false
Copied!
You may now use your model :
1
a = Article.new({name: "A superb article!" })
2
a.description = "This is a master piece!"
3
a.save!
4
5
puts "Article has been properly saved as id=#{a.id}"
Copied!
By default, Clear will inflect the model name and use plural lower case version of the model name as table name (here articles).
You may want to override this behavior, by redefining self.table :
1
class Model::Customer
2
include Clear::Model
3
4
self.table = "clients" #< Different from infered "model_customers" table.
5
# ...
6
end
Copied!
Next article is covering deeply the column definition and its subtleties.
Last modified 1yr ago
Copy link