Skip to content

Commit

Permalink
Update the Ecto associations
Browse files Browse the repository at this point in the history
  • Loading branch information
shamshirz committed Jun 19, 2018
1 parent bb624aa commit 0d403a7
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 9 deletions.
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,26 @@ Let's make sure it works

`mix test`

** Note to self, possibly add Player.games & Game.players as `has_many:through`? **
This is nice, but I want to have the associations available on my Structs.
Updating this is pretty easy, we can just replace the foreign binary_ids with the `[has_*, belongs_*] macros.

In `Scoreboard.Games.Score` Replace

```elixir
field :player_id, :binary_id
field :game_id, :binary_id
```

With

```elixir
belongs_to(:game, Game)
belongs_to(:player, Player)
```

I added the associations to the `Game` and `Player` schemas as well.

Test again and make sure everything is still okay `mix test`


### Absinthe
Expand Down
7 changes: 5 additions & 2 deletions lib/scoreboard/games/game.ex
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
defmodule Scoreboard.Games.Game do
use Ecto.Schema
import Ecto.Changeset

alias Scoreboard.Games.{Player, Score}

@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "games" do
field :name, :string
field(:name, :string)

has_many(:scores, Score)
many_to_many(:players, Player, join_through: Score)

timestamps()
end
Expand Down
7 changes: 5 additions & 2 deletions lib/scoreboard/games/player.ex
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
defmodule Scoreboard.Games.Player do
use Ecto.Schema
import Ecto.Changeset

alias Scoreboard.Games.{Game, Score}

@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "players" do
field :name, :string
field(:name, :string)

has_many(:scores, Score)
many_to_many(:games, Game, join_through: Score)

timestamps()
end
Expand Down
8 changes: 4 additions & 4 deletions lib/scoreboard/games/score.ex
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
defmodule Scoreboard.Games.Score do
use Ecto.Schema
import Ecto.Changeset

alias Scoreboard.Games.{Game, Player}

@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "scores" do
field :total, :integer
field :player_id, :binary_id
field :game_id, :binary_id
field(:total, :integer)
belongs_to(:game, Game)
belongs_to(:player, Player)

timestamps()
end
Expand Down

0 comments on commit 0d403a7

Please sign in to comment.