-
Notifications
You must be signed in to change notification settings - Fork 108
feat: refactor player and album relationship to many-to-many #127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,225 @@ | ||
| # Refactoring de relacionamento | ||
| # Ruby Dev Test 2 - Refactoring de Relacionamento | ||
|
|
||
| > A Madonna resolveu lançar um album em parceria com a Shakira! E agora?! | ||
| ## Objetivo | ||
|
|
||
| Nosso PO jamais iria esperar que um album pudesse ter mais de um artista. Transforme a relacão 1 para N entre Player e Album em uma relação N para N. Precisamos de testes senão o chato do agilista vai brigar conosco! | ||
| Este projeto implementa o refactoring da relação entre `Player` e `Album`, alterando o relacionamento original de **1 para N** para **N para N**. | ||
|
|
||
| O cenário proposto considera que um álbum pode possuir mais de um artista, como no exemplo de uma colaboração entre Madonna e Shakira. | ||
|
|
||
| --- | ||
|
|
||
| ## Resumo da Mudança | ||
|
|
||
| Antes do refactoring, a modelagem era: | ||
|
|
||
| - `Player has_many :albums` | ||
| - `Album belongs_to :player` | ||
|
|
||
| Isso implicava a existência de uma coluna `player_id` na tabela `albums`, permitindo apenas um artista por álbum. | ||
|
|
||
| Após o refactoring, a modelagem passou a ser: | ||
|
|
||
| - `Player has_many :player_albums` | ||
| - `Player has_many :albums, through: :player_albums` | ||
| - `Album has_many :player_albums` | ||
| - `Album has_many :players, through: :player_albums` | ||
|
|
||
| Foi criada a tabela de junção `player_albums`, permitindo que um álbum esteja associado a múltiplos artistas. | ||
|
|
||
| --- | ||
|
|
||
| ## Principais Mudanças | ||
|
|
||
| ### 1. Criação da tabela de junção | ||
|
|
||
| Foi criada a tabela `player_albums` para representar o relacionamento N para N entre artistas e álbuns. | ||
|
|
||
| Essa tabela contém: | ||
|
|
||
| - `player_id` | ||
| - `album_id` | ||
|
|
||
| Também foi adicionado um índice único para impedir duplicidade do mesmo relacionamento entre artista e álbum. | ||
|
|
||
| --- | ||
|
|
||
| ### 2. Migração dos dados existentes | ||
|
|
||
| Como o projeto original já possuía uma relação `albums.player_id`, foi criada uma migration de dados para preservar os vínculos existentes. | ||
|
|
||
| Essa migration copia os dados da relação antiga para a nova tabela `player_albums`. | ||
|
|
||
| ### Por que usar migration para isso? | ||
|
|
||
| A migração de dados foi implementada em uma migration, e não em uma rake task, porque a transformação faz parte da evolução versionada do schema e precisa acontecer na ordem correta junto com as demais alterações estruturais. | ||
|
|
||
| Com isso, garantimos que: | ||
|
|
||
| - a criação da join table acontece antes do backfill | ||
| - os dados antigos são migrados antes da remoção da foreign key antiga | ||
| - qualquer ambiente que rode `db:migrate` chegue ao mesmo estado final | ||
|
|
||
| Uma rake task seria manual e não garantiria execução nem ordem correta. | ||
|
|
||
| --- | ||
|
|
||
| ### 3. Remoção da foreign key antiga | ||
|
|
||
| Após a migração dos dados, a coluna `player_id` foi removida da tabela `albums`. | ||
|
|
||
| --- | ||
|
|
||
| ### 4. Ajuste dos models | ||
|
|
||
| Os models foram atualizados para refletir o novo relacionamento N para N: | ||
|
|
||
| - `Player` | ||
| - `Album` | ||
| - `PlayerAlbum` | ||
|
|
||
| Também foi adicionada validação de unicidade na join table para impedir duplicidade do mesmo par `player` + `album`. | ||
|
|
||
| --- | ||
|
|
||
| ### 5. Atualização dos testes | ||
|
|
||
| Os testes foram adaptados para validar o novo comportamento: | ||
|
|
||
| - `Album` deixa de exigir `player` | ||
| - `Player` pode ter vários álbuns | ||
| - `Album` pode ter vários artistas | ||
| - `PlayerAlbum` garante presença e unicidade do relacionamento | ||
|
|
||
| Também foram ajustadas as fixtures para refletir o novo modelo. | ||
|
|
||
| --- | ||
|
|
||
| ## Decisões de Projeto | ||
|
|
||
| ### Manter a stack original | ||
|
|
||
| O projeto foi mantido na stack original: | ||
|
|
||
| - Ruby 2.4.1 | ||
| - Rails 5.2 | ||
| - SQLite | ||
| - Minitest | ||
|
|
||
| A decisão foi preservar o escopo do exercício e evitar misturar o refactoring de domínio com um upgrade de stack. | ||
|
|
||
| ### Dependência `mimemagic` | ||
|
|
||
| Foi necessário ajustar a dependência transitiva `mimemagic`, pois a versão originalmente referenciada no lockfile não está mais disponível no RubyGems. | ||
|
|
||
| A correção foi feita de forma mínima, apenas para restaurar a execução do projeto, sem promover upgrades amplos de dependências. | ||
|
|
||
| ### Runtime JavaScript | ||
|
|
||
| Foi necessário ter um runtime JavaScript disponível no ambiente para o `uglifier` funcionar corretamente. A solução adotada foi instalar Node.js no ambiente local. | ||
|
|
||
| --- | ||
|
|
||
| ## Estrutura Final do Relacionamento | ||
|
|
||
| ### Antes | ||
|
|
||
| ```ruby | ||
| class Album < ApplicationRecord | ||
| belongs_to :player | ||
| end | ||
|
|
||
| class Player < ApplicationRecord | ||
| has_many :albums | ||
| end | ||
| ``` | ||
|
|
||
| ### Depois | ||
|
|
||
| ```ruby | ||
| class Album < ApplicationRecord | ||
| has_many :player_albums, dependent: :destroy | ||
| has_many :players, through: :player_albums | ||
| end | ||
|
|
||
| class Player < ApplicationRecord | ||
| has_many :player_albums, dependent: :destroy | ||
| has_many :albums, through: :player_albums | ||
| end | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Como rodar o projeto | ||
|
|
||
| ## Pré-requisitos | ||
|
|
||
| - Ruby 2.4.1 | ||
| - Bundler 1.16.1 | ||
| - SQLite3 | ||
| - Node.js | ||
|
|
||
| --- | ||
|
|
||
| ## Instalação | ||
|
|
||
| ### 1. Clonar o repositório | ||
|
|
||
| ```bash | ||
| git clone git@github.com:flaviolpgjr/ruby-dev-test-2.git | ||
| cd ruby-dev-test-2 | ||
| ``` | ||
|
|
||
| ### 2. Instalar dependências Ruby | ||
|
|
||
| ```bash | ||
| bundle _1.16.1_ install | ||
| ``` | ||
|
|
||
| ### 3. Preparar o banco | ||
|
|
||
| ```bash | ||
| bundle _1.16.1_ exec rails db:create | ||
| bundle _1.16.1_ exec rails db:migrate | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Rodar os testes | ||
|
|
||
| ```bash | ||
| bundle _1.16.1_ exec rails test | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## O que os testes validam | ||
|
|
||
| ### `AlbumTest` | ||
| - álbum válido com nome | ||
| - presença de nome | ||
| - relacionamento com múltiplos artistas | ||
|
|
||
| ### `PlayerTest` | ||
| - player válido com nome | ||
| - presença de nome | ||
| - relacionamento com múltiplos álbuns | ||
|
|
||
| ### `PlayerAlbumTest` | ||
| - relacionamento válido | ||
| - presença de `player` | ||
| - presença de `album` | ||
| - unicidade do par `player` + `album` | ||
|
|
||
| --- | ||
|
|
||
| ## Considerações Finais | ||
|
|
||
| A solução foi construída com foco em: | ||
|
|
||
| - preservação dos dados existentes | ||
| - simplicidade | ||
| - clareza do refactoring | ||
| - cobertura de testes | ||
| - respeito ao escopo do exercício | ||
|
|
||
| O refactoring foi implementado em etapas para reduzir risco e garantir consistência durante a transição do relacionamento 1 para N para um relacionamento N para N. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| class Album < ApplicationRecord | ||
| belongs_to :player | ||
| has_many :player_albums, dependent: :destroy | ||
| has_many :players, through: :player_albums | ||
|
|
||
| validates_presence_of :name | ||
| end | ||
| end |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| class Player < ApplicationRecord | ||
| has_many :albums | ||
| has_many :player_albums, dependent: :destroy | ||
| has_many :albums, through: :player_albums | ||
|
|
||
| validates_presence_of :name | ||
| end | ||
| end |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| class PlayerAlbum < ApplicationRecord | ||
| belongs_to :player | ||
| belongs_to :album | ||
|
|
||
| validates :player_id, uniqueness: { scope: :album_id } | ||
| end |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| class CreatePlayerAlbums < ActiveRecord::Migration[5.2] | ||
| def change | ||
| create_table :player_albums do |t| | ||
| t.references :player, foreign_key: true, null: false | ||
| t.references :album, foreign_key: true, null: false | ||
|
|
||
| t.timestamps | ||
| end | ||
|
|
||
| add_index :player_albums, [:player_id, :album_id], unique: true | ||
| end | ||
| end |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,16 @@ | ||||||||||||||||||||||||||||||||||||||||
| class MigrateAlbumPlayerToPlayerAlbums < ActiveRecord::Migration[5.2] | ||||||||||||||||||||||||||||||||||||||||
| def up | ||||||||||||||||||||||||||||||||||||||||
| Album.reset_column_information | ||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||
| Album.where.not(player_id: nil).find_each do |album| | ||||||||||||||||||||||||||||||||||||||||
| PlayerAlbum.find_or_create_by!( | ||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+2
to
+6
|
||||||||||||||||||||||||||||||||||||||||
| def up | |
| Album.reset_column_information | |
| Album.where.not(player_id: nil).find_each do |album| | |
| PlayerAlbum.find_or_create_by!( | |
| class MigrationAlbum < ActiveRecord::Base | |
| self.table_name = "albums" | |
| end | |
| class MigrationPlayerAlbum < ActiveRecord::Base | |
| self.table_name = "player_albums" | |
| end | |
| def up | |
| MigrationAlbum.reset_column_information | |
| MigrationPlayerAlbum.reset_column_information | |
| MigrationAlbum.where.not(player_id: nil).find_each do |album| | |
| MigrationPlayerAlbum.find_or_create_by!( |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| class RemovePlayerIdFromAlbums < ActiveRecord::Migration[5.2] | ||
| def change | ||
| remove_reference :albums, :player, foreign_key: true | ||
| end | ||
| end |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,11 @@ | ||
| fijacion: | ||
| name: Fijación Oral, Vol. 1 | ||
| player: shakira | ||
|
|
||
| fixation: | ||
| oral_fixation: | ||
| name: Oral Fixation, Vol. 2 | ||
| player: shakira | ||
|
|
||
| fixation: | ||
| she_wolf: | ||
| name: She Wolf | ||
| player: shakira | ||
|
|
||
| collab_album: | ||
| name: Madonna & Shakira |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| shakira_fijacion: | ||
| player: shakira | ||
| album: fijacion | ||
|
|
||
| shakira_oral_fixation: | ||
| player: shakira | ||
| album: oral_fixation | ||
|
|
||
| shakira_she_wolf: | ||
| player: shakira | ||
| album: she_wolf | ||
|
|
||
| madonna_collab: | ||
| player: madonna | ||
| album: collab_album | ||
|
|
||
| shakira_collab: | ||
| player: shakira | ||
| album: collab_album |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,3 +3,6 @@ beyonce: | |
|
|
||
| shakira: | ||
| name: Shakira | ||
|
|
||
| madonna: | ||
| name: Madonna | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Gemfile consistently uses single-quoted strings, but this new gem declaration uses double quotes. For consistency with the existing style in this file, switch this line to single quotes.