Repositories » Quick Start
This documentation uses
rom-sql as an example. For in-depth information see
documentation for specific databases.
You can quickly create a schema inside the setup block. Let's configure our
SQL gateway and create a
require 'rom' rom = ROM.container(:sql, 'sqlite::memory') do |conf| conf.default.create_table(:users) do primary_key :id column :name, String, null: false column :email, String, null: false end class Users < ROM::Relation[:sql] schema(infer: true) end conf.register_relation(Users) end
A Repository ("Repo") object provides a lot of conveniences for reading data with relations. Every repo can access one or more relations, depending on how you set it up.
To set up a repo to work with our
:users relation simply define a class like
require 'rom-repository' class UserRepo < ROM::Repository[:users] end
Repositories must be instantiated with a rom container passed to the constructor, this gives access to all components within the container:
user_repo = UserRepo.new(rom)
Let's see how Create, Update and Delete commands work with repositories.
A repo can be configured to provide access to
require 'rom-repository' class UserRepo < ROM::Repository[:users] commands :create end
commands macro defines a
UserRepo#create method for us:
user_repo.create(name: "Jane", email: "email@example.com") # => #<ROM::Struct[User] id=1 name="Jane" email="firstname.lastname@example.org">
By default, repos return simple
ROM::Struct objects. You'll learn more about them in
Update and Delete commands require restricting relations so that ROM knows exactly which records to modify. Provide :update and :delete with the symbol name of the method to call to get that restricted relation.
The most popular adapter, rom-sql, automatically defines a method,
restricts by the primary key. In projects with rom-sql, we would use it to define
update and delete commands in a repo:
require 'rom-repository' class UserRepo < ROM::Repository[:users] commands :create, update: :by_pk, delete: :by_pk end
Now we have a full
CRUD setup, we can create, update and delete user data:
user = user_repo.create(name: "Jane", email: "email@example.com") # => #<ROM::Struct[User] id=1 name="Jane" email="firstname.lastname@example.org"> # let's update the user updated_user = user_repo.update(user.id, name: "Jane Doe") # => #<ROM::Struct[User] id=1 name="Jane Doe" email="email@example.com"> # and now let's delete the user user_repo.delete(user.id)
Now that you know how to create tables and define repositories with full CRUD support, you can proceed to reading section.