Skip to content

Commit

Permalink
[ci skip] Fix shard docs
Browse files Browse the repository at this point in the history
We never explained how migrations paths work for shards. This fixes that
and also adds the appropriate class setup. You no longer need to set a
`default` shard as of #48353. In addition, `ApplicationRecord` should be
used for the non-sharded db that also serves as the tenant/shard router.
Then shards should get their own connection class since the schema
differs.
  • Loading branch information
eileencodes committed Oct 16, 2023
1 parent 2872d55 commit 35e0ae4
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions guides/source/active_record_multiple_databases.md
Expand Up @@ -407,10 +407,21 @@ production:
primary_shard_one:
database: my_primary_shard_one
adapter: mysql2
migrations_paths: db/migrate_shards
primary_shard_one_replica:
database: my_primary_shard_one
adapter: mysql2
replica: true
migrations_paths: db/migrate_shards
primary_shard_two:
database: my_primary_shard_two
adapter: mysql2
migrations_paths: db/migrate_shards
primary_shard_two_replica:
database: my_primary_shard_two
adapter: mysql2
replica: true
migrations_paths: db/migrate_shards
```

Models are then connected with the `connects_to` API via the `shards` key:
Expand All @@ -419,18 +430,27 @@ Models are then connected with the `connects_to` API via the `shards` key:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true

connects_to database: { writing: :primary, reading: :primary_replica }
end

class ShardRecord < ApplicationRecord
connects_to shards: {
default: { writing: :primary, reading: :primary_replica },
shard_one: { writing: :primary_shard_one, reading: :primary_shard_one_replica }
shard_two: { writing: :primary_shard_two, reading: :primary_shard_two_replica }

This comment has been minimized.

Copy link
@seanpdoyle

seanpdoyle Oct 16, 2023

Contributor

@eileencodes I think this docs change broke linting in CI. I've opened #49660 to try and resolve that failure.

}
end
```

You are not required to use `default` as the first shard name. Rails will assume the first
shard name in the `connects_to` hash is the "default" connection. This connection is used
internally to load type data and other information where the schema is the same across shards.
If you're using shards, make sure to set the `migrations_paths` to the same path for
all the shards. When generating a migration you can pass the `--database` option and
use one of the shard names. Since they all set the same path, it doesn't matter which
one you choose.

```
$ bin/rails g scaffold Dog name:string --database primary_shard_one
```

Then models can swap connections manually via the `connected_to` API. If
Then models can swap shards manually via the `connected_to` API. If
using sharding, both a `role` and a `shard` must be passed:

```ruby
Expand Down

0 comments on commit 35e0ae4

Please sign in to comment.