See all articles

Dashboards for a Rails app on PostgreSQL with Metabase

To give your team dashboards over your Rails app’s PostgreSQL database, connect Metabase to it with a read-only role that you create in a Rails migration. Run Metabase on Metabase Cloud or as a service in your docker-compose.yml, and give it the host and database name from config/database.yml. Your team then builds charts with the query builder or SQL, and a dashboard subscription sends them by email or Slack every week, with no new code in your app.

Metabase’s Open Source edition is free to self-host with unlimited users, and dashboard subscriptions come with every plan. Metabase Cloud Starter costs $100 a month with 5 users included, and it starts with a 14-day free trial (prices checked on November 12, 2026). If you’re still choosing between dashboards built into your app and a BI tool, start with our guide to internal dashboards. This recipe also exists for Django, Next.js and Go.

How do I create a read-only Postgres user for Metabase in Rails?

Metabase recommends a dedicated metabase database user with read-only access. Create it in a migration, so every environment gets the same role and your team reviews it like any other change:

bin/rails generate migration AddMetabaseReadonlyRole

Fill in the new file as below, and keep the version number that the generator wrote in the brackets. The SQL follows the “Minimum database privileges” example in the Metabase docs, with the option that grants read access to specific tables:

class AddMetabaseReadonlyRole < ActiveRecord::Migration[8.1]
  def up
    execute <<~SQL
      -- Roles belong to the whole PostgreSQL server, so create them only once.
      DO $$
      BEGIN
        IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'analytics') THEN
          CREATE ROLE analytics;
        END IF;
        IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'metabase') THEN
          CREATE USER metabase; -- no password here: set it outside the migration
        END IF;
        -- Each environment has its own database name, so read it from the connection.
        EXECUTE format('GRANT CONNECT ON DATABASE %I TO analytics', current_database());
      END
      $$;

      GRANT analytics TO metabase;
      GRANT USAGE ON SCHEMA public TO analytics;
      -- List the tables your teams need. Leave out tables with password hashes, tokens or sessions.
      GRANT SELECT ON TABLE public.orders, public.customers TO analytics;
    SQL
  end

  def down
    execute <<~SQL
      -- Revokes the privileges in this database. The roles stay for other databases.
      REVOKE SELECT ON TABLE public.orders, public.customers FROM analytics;
      REVOKE USAGE ON SCHEMA public FROM analytics;
      DO $$
      BEGIN
        EXECUTE format('REVOKE CONNECT ON DATABASE %I FROM analytics', current_database());
      END
      $$;
    SQL
  end
end

Roles belong to the whole PostgreSQL server, and your development and test databases often share one server, so the migration creates each role only when it’s missing. current_database() names each environment’s database. Replace orders and customers with the tables your teams need, leave out tables that hold password digests, tokens or sessions, and grant each new table in the migration that creates it. To create roles, your app’s database user needs the CREATEROLE attribute or superuser rights. If it has neither, ask whoever runs the database to create both roles, run GRANT analytics TO metabase and set the password. Then delete that GRANT analytics TO metabase; line from your migration, because PostgreSQL refuses it for a user without those rights, and refuses \password metabase too.

The password stays out of the migration and out of Git. Run the migration, then open psql with bin/rails dbconsole, which reads config/database.yml for the current Rails environment. Each database server keeps its own roles, so set the password on every server that Metabase connects to, such as production:

bin/rails db:migrate
bin/rails dbconsole

At the psql prompt, run \password metabase and type the new password twice. psql encrypts the password before it sends it, so it doesn’t appear in your shell history or in the server log.

Where does Rails keep the settings for Metabase’s connection form?

Rails reads its database settings from config/database.yml or the DATABASE_URL environment variable, and merges the two when both exist. Metabase needs the host, port and database name from your production settings. In a URL such as postgresql://app_user:PASSWORD@db.example.com:5432/app_production, those are db.example.com, 5432 and app_production, and for the username you use metabase, not your app’s own user.

If your app reads from a replica, config/database.yml has a second entry for it with replica: true, for example:

production:
  primary:
    url: <%= ENV["DATABASE_URL"] %>
  primary_replica:
    url: <%= ENV["PRIMARY_REPLICA_DATABASE_URL"] %>
    replica: true

Give Metabase the replica’s host, so dashboard queries don’t add load to the primary. A replica accepts only read-only queries and Rails doesn’t run migrations against it, so the migration runs on the primary. A streaming replica, such as an Amazon RDS for PostgreSQL read replica, then receives the new role and its password, so metabase can sign in there too. On a PostgreSQL replica, changes from the primary can cancel a long query. For a replica that serves dashboards, the PostgreSQL docs suggest a high max_standby_streaming_delay.

How do I run Metabase next to a Rails app?

Metabase Cloud. Start a trial from the pricing page, and Metabase runs, backs up and upgrades the server for you. Metabase Cloud connects to your database from three fixed IP addresses in each region, so allow them in your database’s firewall or security group. If the database has no public endpoint, connect through an SSH tunnel, as Dashboards on a private database explains.

Docker Compose. Add Metabase to your app’s docker-compose.yml, with a small Postgres of its own for its application database, which holds Metabase’s users, questions and dashboards apart from your app’s data. This excerpt comes from Run Metabase in production with Docker, which explains every setting:

# Add to your docker-compose.yml (Postgres names changed to avoid clashes).
services:
  metabase:
    # Pin a full version. Replace it with the newest release in
    # https://www.metabase.com/changelog/65
    image: metabase/metabase:v0.65.4.1
    restart: unless-stopped
    ports:
      - "127.0.0.1:3000:3000" # only this host can connect; put a reverse proxy with TLS in front
    environment:
      MB_DB_TYPE: postgres
      MB_DB_DBNAME: metabaseappdb
      MB_DB_PORT: 5432
      MB_DB_USER: metabase
      MB_DB_PASS_FILE: /run/secrets/metabase_db_password
      MB_DB_HOST: metabase-postgres
      MB_ENCRYPTION_SECRET_KEY: ${MB_ENCRYPTION_SECRET_KEY:?set MB_ENCRYPTION_SECRET_KEY in .env}
      MB_SITE_URL: https://metabase.example.com
      JAVA_OPTS: -Xmx2g
      JAVA_TIMEZONE: UTC # match the time zone of your reports
    secrets:
      - metabase_db_password
    mem_limit: 3g
    depends_on:
      metabase-postgres:
        condition: service_healthy
    healthcheck:
      test: curl --fail -I http://localhost:3000/api/health || exit 1
      interval: 15s
      timeout: 5s
      retries: 5
      start_period: 5m

  metabase-postgres:
    image: postgres:17 # with postgres:18 and later, mount the volume at /var/lib/postgresql
    restart: unless-stopped
    environment:
      POSTGRES_USER: metabase
      POSTGRES_DB: metabaseappdb
      POSTGRES_PASSWORD_FILE: /run/secrets/metabase_db_password
    secrets:
      - metabase_db_password
    volumes:
      - metabase_pg_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U metabase -d metabaseappdb"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  metabase_pg_data:

secrets:
  metabase_db_password:
    file: ./metabase_db_password.txt

Create the encryption key and the password file, then start Metabase, and Compose starts metabase-postgres with it. The >> adds the key to your existing .env file instead of replacing it, and both files should stay out of Git:

echo "MB_ENCRYPTION_SECRET_KEY=$(openssl rand -base64 32)" >> .env
openssl rand -base64 24 > metabase_db_password.txt
docker compose up -d metabase

Open Metabase through your reverse proxy, or at http://localhost:3000 on the Docker host, and create the first admin account. If your app’s Postgres runs in the same compose file, use its service name, such as db, as the host in the next step, not localhost, because Metabase connects from inside its own container.

How do I connect the Rails database in Metabase?

Click the grid icon at the top right, go to Admin > Databases, click Add database and choose PostgreSQL. Fill in the form with your Rails settings:

  • Display name: any name, such as “Rails app”.
  • Host: the primary’s host, or the replica’s.
  • Port: usually 5432.
  • Database name: for example app_production.
  • Username: metabase.
  • Password: the password you set with \password.

Keep Use a secure connection (SSL) on when your database supports it, as Metabase recommends, and turn on Use an SSH tunnel only for a bastion host. Click Save, and Metabase syncs the schema right away and then every hour by default, so each table that a later migration grants shows up on its own.

How do I build a first question and a dashboard?

Start with orders per week, from the orders table of an Order model:

  1. Click + New > Dashboard, name it “Weekly metrics”, pick a collection and click Create.
  2. Click + New > Question and pick the Orders table. Metabase shows orders as Orders and created_at as Created At, because it makes table and column names more readable by default.
  3. In the Summarize step, pick Count of rows and group by Created At, then click by month and change it to week.
  4. Click Visualize, then Save, and save the question to the Weekly metrics dashboard. Place the card and save the dashboard.

If your team prefers SQL, click + New > SQL query, run this query with the read-only role and save it to the same dashboard:

-- Orders per week, for this week and the 12 weeks before it. Weeks start on Monday.
SELECT date_trunc('week', created_at) AS week, count(*) AS orders
FROM orders
WHERE created_at >= date_trunc('week', now()) - interval '12 weeks'
GROUP BY 1
ORDER BY 1;

PostgreSQL’s date_trunc starts weeks on Monday, while the query builder starts them on Sunday by default, so set First day of the week to Monday in Admin > Settings > Localization if you use both. By default, Rails creates created_at as a timestamp without time zone column and reads its values as UTC, so these weeks follow UTC.

How do I email or Slack the dashboard every week?

An admin sets up email or Slack once. On Metabase Cloud, Metabase manages an email server for you, so email works right away. On a self-hosted Metabase, go to Admin > Settings > Email, click Configure next to Self-Hosted SMTP and enter your SMTP server’s details. For Slack, go to Admin > Settings > Slack, click Create Slack App and install the app in your workspace. Then paste its Bot User OAuth Token into Slack bot user OAuth token and click Connect.

Then create the subscription on the dashboard:

  1. Open the dashboard and click the Subscriptions icon at the top right, next to the edit and sharing icons.
  2. Choose email or Slack, then add Metabase users by name, anyone else by email address, or a Slack channel such as #metrics.
  3. Set the frequency to Weekly, then pick the day and the time.
  4. Click Send email/Slack now to check the message, then save the subscription. The test goes to every recipient, so Metabase suggests that you test with only your own address first and add the team after.

Recipients don’t need a Metabase account, and they see the data that the subscription’s creator can see. You don’t need a refresh job, because Metabase runs the dashboard’s questions against your database each time it sends. An email can attach the results as .csv or .xlsx files, and any subscription can attach a PDF of the dashboard.

Next steps

# Dashboards for a Rails app on PostgreSQL with Metabase

To give your team dashboards over your Rails app's PostgreSQL database, connect Metabase to it with a read-only role that you create in a Rails migration. Run Metabase on Metabase Cloud or as a service in your `docker-compose.yml`, and give it the host and database name from `config/database.yml`. Your team then builds charts with the query builder or SQL, and a dashboard subscription sends them by email or Slack every week, with no new code in your app.

Metabase's Open Source edition is free to self-host with unlimited users, and dashboard subscriptions come with every plan. Metabase Cloud Starter costs $100 a month with 5 users included, and it starts with a 14-day free trial (prices checked on November 12, 2026). If you're still choosing between dashboards built into your app and a BI tool, start with [our guide to internal dashboards](/articles/internal-dashboards). This recipe also exists for [Django](/articles/dashboards-for-django-apps), [Next.js](/articles/dashboards-for-nextjs-apps) and [Go](/articles/dashboards-for-go-apps).

## How do I create a read-only Postgres user for Metabase in Rails?

Metabase recommends a dedicated `metabase` database user with read-only access. Create it in a migration, so every environment gets the same role and your team reviews it like any other change:

```bash
bin/rails generate migration AddMetabaseReadonlyRole
```

Fill in the new file as below, and keep the version number that the generator wrote in the brackets. The SQL follows the "Minimum database privileges" example in the Metabase docs, with the option that grants read access to specific tables:

```rb
class AddMetabaseReadonlyRole < ActiveRecord::Migration[8.1]
  def up
    execute <<~SQL
      -- Roles belong to the whole PostgreSQL server, so create them only once.
      DO $$
      BEGIN
        IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'analytics') THEN
          CREATE ROLE analytics;
        END IF;
        IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'metabase') THEN
          CREATE USER metabase; -- no password here: set it outside the migration
        END IF;
        -- Each environment has its own database name, so read it from the connection.
        EXECUTE format('GRANT CONNECT ON DATABASE %I TO analytics', current_database());
      END
      $$;

      GRANT analytics TO metabase;
      GRANT USAGE ON SCHEMA public TO analytics;
      -- List the tables your teams need. Leave out tables with password hashes, tokens or sessions.
      GRANT SELECT ON TABLE public.orders, public.customers TO analytics;
    SQL
  end

  def down
    execute <<~SQL
      -- Revokes the privileges in this database. The roles stay for other databases.
      REVOKE SELECT ON TABLE public.orders, public.customers FROM analytics;
      REVOKE USAGE ON SCHEMA public FROM analytics;
      DO $$
      BEGIN
        EXECUTE format('REVOKE CONNECT ON DATABASE %I FROM analytics', current_database());
      END
      $$;
    SQL
  end
end
```

Roles belong to the whole PostgreSQL server, and your development and test databases often share one server, so the migration creates each role only when it's missing. `current_database()` names each environment's database. Replace `orders` and `customers` with the tables your teams need, leave out tables that hold password digests, tokens or sessions, and grant each new table in the migration that creates it. To create roles, your app's database user needs the `CREATEROLE` attribute or superuser rights. If it has neither, ask whoever runs the database to create both roles, run `GRANT analytics TO metabase` and set the password. Then delete that `GRANT analytics TO metabase;` line from your migration, because PostgreSQL refuses it for a user without those rights, and refuses `\password metabase` too.

The password stays out of the migration and out of Git. Run the migration, then open psql with `bin/rails dbconsole`, which reads `config/database.yml` for the current Rails environment. Each database server keeps its own roles, so set the password on every server that Metabase connects to, such as production:

```bash
bin/rails db:migrate
bin/rails dbconsole
```

At the psql prompt, run `\password metabase` and type the new password twice. psql encrypts the password before it sends it, so it doesn't appear in your shell history or in the server log.

## Where does Rails keep the settings for Metabase's connection form?

Rails reads its database settings from `config/database.yml` or the `DATABASE_URL` environment variable, and merges the two when both exist. Metabase needs the host, port and database name from your production settings. In a URL such as `postgresql://app_user:PASSWORD@db.example.com:5432/app_production`, those are `db.example.com`, `5432` and `app_production`, and for the username you use `metabase`, not your app's own user.

If your app reads from a replica, `config/database.yml` has a second entry for it with `replica: true`, for example:

```yaml
production:
  primary:
    url: <%= ENV["DATABASE_URL"] %>
  primary_replica:
    url: <%= ENV["PRIMARY_REPLICA_DATABASE_URL"] %>
    replica: true
```

Give Metabase the replica's host, so dashboard queries don't add load to the primary. A replica accepts only read-only queries and Rails doesn't run migrations against it, so the migration runs on the primary. A streaming replica, such as an Amazon RDS for PostgreSQL read replica, then receives the new role and its password, so `metabase` can sign in there too. On a PostgreSQL replica, changes from the primary can cancel a long query. For a replica that serves dashboards, the PostgreSQL docs suggest a high `max_standby_streaming_delay`.

## How do I run Metabase next to a Rails app?

**Metabase Cloud.** Start a trial from the [pricing page](/pricing), and Metabase runs, backs up and upgrades the server for you. Metabase Cloud connects to your database from three fixed IP addresses in each region, so allow them in your database's firewall or security group. If the database has no public endpoint, connect through an SSH tunnel, as [Dashboards on a private database](/articles/dashboards-on-a-private-database) explains.

**Docker Compose.** Add Metabase to your app's `docker-compose.yml`, with a small Postgres of its own for its application database, which holds Metabase's users, questions and dashboards apart from your app's data. This excerpt comes from [Run Metabase in production with Docker](/articles/run-metabase-in-production-with-docker), which explains every setting:

```yaml
# Add to your docker-compose.yml (Postgres names changed to avoid clashes).
services:
  metabase:
    # Pin a full version. Replace it with the newest release in
    # https://www.metabase.com/changelog/65
    image: metabase/metabase:v0.65.4.1
    restart: unless-stopped
    ports:
      - "127.0.0.1:3000:3000" # only this host can connect; put a reverse proxy with TLS in front
    environment:
      MB_DB_TYPE: postgres
      MB_DB_DBNAME: metabaseappdb
      MB_DB_PORT: 5432
      MB_DB_USER: metabase
      MB_DB_PASS_FILE: /run/secrets/metabase_db_password
      MB_DB_HOST: metabase-postgres
      MB_ENCRYPTION_SECRET_KEY: ${MB_ENCRYPTION_SECRET_KEY:?set MB_ENCRYPTION_SECRET_KEY in .env}
      MB_SITE_URL: https://metabase.example.com
      JAVA_OPTS: -Xmx2g
      JAVA_TIMEZONE: UTC # match the time zone of your reports
    secrets:
      - metabase_db_password
    mem_limit: 3g
    depends_on:
      metabase-postgres:
        condition: service_healthy
    healthcheck:
      test: curl --fail -I http://localhost:3000/api/health || exit 1
      interval: 15s
      timeout: 5s
      retries: 5
      start_period: 5m

  metabase-postgres:
    image: postgres:17 # with postgres:18 and later, mount the volume at /var/lib/postgresql
    restart: unless-stopped
    environment:
      POSTGRES_USER: metabase
      POSTGRES_DB: metabaseappdb
      POSTGRES_PASSWORD_FILE: /run/secrets/metabase_db_password
    secrets:
      - metabase_db_password
    volumes:
      - metabase_pg_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U metabase -d metabaseappdb"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  metabase_pg_data:

secrets:
  metabase_db_password:
    file: ./metabase_db_password.txt
```

Create the encryption key and the password file, then start Metabase, and Compose starts `metabase-postgres` with it. The `>>` adds the key to your existing `.env` file instead of replacing it, and both files should stay out of Git:

```bash
echo "MB_ENCRYPTION_SECRET_KEY=$(openssl rand -base64 32)" >> .env
openssl rand -base64 24 > metabase_db_password.txt
docker compose up -d metabase
```

Open Metabase through your reverse proxy, or at `http://localhost:3000` on the Docker host, and create the first admin account. If your app's Postgres runs in the same compose file, use its service name, such as `db`, as the host in the next step, not `localhost`, because Metabase connects from inside its own container.

## How do I connect the Rails database in Metabase?

Click the grid icon at the top right, go to **Admin > Databases**, click **Add database** and choose PostgreSQL. Fill in the form with your Rails settings:

- **Display name**: any name, such as "Rails app".
- **Host**: the primary's host, or the replica's.
- **Port**: usually `5432`.
- **Database name**: for example `app_production`.
- **Username**: `metabase`.
- **Password**: the password you set with `\password`.

Keep **Use a secure connection (SSL)** on when your database supports it, as Metabase recommends, and turn on **Use an SSH tunnel** only for a bastion host. Click **Save**, and Metabase syncs the schema right away and then every hour by default, so each table that a later migration grants shows up on its own.

## How do I build a first question and a dashboard?

Start with orders per week, from the `orders` table of an `Order` model:

1. Click **+ New > Dashboard**, name it "Weekly metrics", pick a collection and click **Create**.
2. Click **+ New > Question** and pick the Orders table. Metabase shows `orders` as Orders and `created_at` as Created At, because it makes table and column names more readable by default.
3. In the Summarize step, pick **Count of rows** and group by **Created At**, then click **by month** and change it to **week**.
4. Click **Visualize**, then **Save**, and save the question to the Weekly metrics dashboard. Place the card and save the dashboard.

If your team prefers SQL, click **+ New > SQL query**, run this query with the read-only role and save it to the same dashboard:

```sql
-- Orders per week, for this week and the 12 weeks before it. Weeks start on Monday.
SELECT date_trunc('week', created_at) AS week, count(*) AS orders
FROM orders
WHERE created_at >= date_trunc('week', now()) - interval '12 weeks'
GROUP BY 1
ORDER BY 1;
```

PostgreSQL's `date_trunc` starts weeks on Monday, while the query builder starts them on Sunday by default, so set **First day of the week** to Monday in **Admin > Settings > Localization** if you use both. By default, Rails creates `created_at` as a `timestamp without time zone` column and reads its values as UTC, so these weeks follow UTC.

## How do I email or Slack the dashboard every week?

An admin sets up email or Slack once. On Metabase Cloud, Metabase manages an email server for you, so email works right away. On a self-hosted Metabase, go to **Admin > Settings > Email**, click **Configure** next to **Self-Hosted SMTP** and enter your SMTP server's details. For Slack, go to **Admin > Settings > Slack**, click **Create Slack App** and install the app in your workspace. Then paste its **Bot User OAuth Token** into **Slack bot user OAuth token** and click **Connect**.

Then create the subscription on the dashboard:

1. Open the dashboard and click the **Subscriptions** icon at the top right, next to the edit and sharing icons.
2. Choose email or Slack, then add Metabase users by name, anyone else by email address, or a Slack channel such as #metrics.
3. Set the frequency to **Weekly**, then pick the day and the time.
4. Click **Send email/Slack now** to check the message, then save the subscription. The test goes to every recipient, so Metabase suggests that you test with only your own address first and add the team after.

Recipients don't need a Metabase account, and they see the data that the subscription's creator can see. You don't need a refresh job, because Metabase runs the dashboard's questions against your database each time it sends. An email can attach the results as .csv or .xlsx files, and any subscription can attach a PDF of the dashboard.

## Next steps

- [Database users, roles, and privileges](/docs/latest/databases/users-roles-privileges)
- [Connect Metabase to PostgreSQL](/docs/latest/databases/connections/postgresql)
- [Run Metabase in production with Docker](/articles/run-metabase-in-production-with-docker)
- [Dashboards on a private database](/articles/dashboards-on-a-private-database)
- [Dashboard subscriptions](/docs/latest/dashboards/subscriptions) and [scheduled email and Slack reports](/articles/scheduled-email-slack-reports)
- [Start free with Open Source or Metabase Cloud](/articles/start-free-open-source-or-cloud)
- [Internal dashboards: build them in your app or add Metabase](/articles/internal-dashboards)
- The same recipe for [Django](/articles/dashboards-for-django-apps), [Next.js](/articles/dashboards-for-nextjs-apps) and [Go](/articles/dashboards-for-go-apps)