Working With Data in Hanami

As mentioned earlier, in Hanami, entities, repositories, and relations make up what we call the data layer.

“Relations” define how data is fetched from the database. You would also define scopes and other database-specific queries in relations.

“Repositories”, however, are database-agnostic. They mediate between entities and relations.

An “entity” is where you define domain-specific logic.

After this very condensed overview of the Hanami data layer, let’s continue with creating some data for our app.

We could manually create migration files, but since we have access to the awesome Hanami CLI generator (although it has limited functionality for now), let’s use it to create a migration that will be used to create the blogs table for our app.

The other reason we want to create migrations using the CLI, other than convenience, is because we want the timestamps applied automatically.

hanami db create_migration blogs

This creates a migration under the db folder. For now, this file is a bit empty and rather useless to us. Edit it as follows:

# frozen_string_literal: true

ROM::SQL.migration do
  change do
    create_table(:blogs) do
      primary_key :id
      column :title, String 
      column :body, String 

      column :created_at, DateTime, null: false
      column :updated_at, DateTime, null: false
    end
  end
end

Then apply the migration to create the blogs table.

hanami db migrate

For the purposes of our very simple blog app, we will seed the table with some data.

Find the seeds file (under the db folder) and edit it accordingly.

# Seeds

# create some blogs
blogs = Main::Container['application.persistence.repositories.blogs']

20.times do |i|
    blogs.create(title: "Blog no.#{i}", body: "This is blog no. #{i}", created_at: Time.now, updated_at: Time.now)
end

Then run it:

hanami db seed

With that, we should now have a few blog posts to work with.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *