Clear ORM
Search…
The collection object
Each model offers an object called ModelName::Collection. This Collection object offers a way to query the database and perform operations on large groups of model.
To instantiate a new Collection, you can simply call the method query over the model class:
1
users = User.query
Copied!

Collection and SELECT query

When instantiated, the collection is Crystal implementation of a SELECT query:
1
-- Users.query ==
2
SELECT * FROM users
Copied!
Therefore, calling to_a over the Collection will fetch all the models from the database to your crystal code:
1
array_of_users = User.query.to_a
Copied!
Collection will really perform SQL request only on resolution time, when calling each or to_a for example.

Mutability

Collection are mutable objects, and many of the methods will change the state of the collection:
1
query = User.query # SELECT * FROM users;
2
query.select("id") # SELECT id FROM users;
3
query.select("id") # SELECT id, id FROM users;
Copied!
Therefore, you may want to use Collection#dup to duplicate the current state of the collection:
1
query = User.query # SELECT * FROM users;
2
query.select("id") # SELECT id FROM users;
3
4
query2 = collection.dup # SELECT id FROM users;
Copied!
Collection can be filtered and refined to query exactly what you want. Actually, they are refined version of SQL::SelectBuilder object described in Low-level SQL chapter.
Last modified 1yr ago